| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| node-npmtest-yarn/ | 100% | (153 / 153) | 100% | (126 / 126) | 100% | (28 / 28) | 100% | (153 / 153) | |
| node-npmtest-yarn/node_modules/yarn/bin/ | 79.17% | (19 / 24) | 50% | (5 / 10) | 100% | (0 / 0) | 79.17% | (19 / 24) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/ | 17.05% | (243 / 1425) | 3.23% | (24 / 743) | 5.33% | (12 / 225) | 17.32% | (239 / 1380) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/lockfile/ | 21.81% | (77 / 353) | 2.83% | (7 / 247) | 10.42% | (5 / 48) | 22.29% | (76 / 341) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/registries/ | 27.57% | (83 / 301) | 5.83% | (12 / 206) | 7.81% | (5 / 64) | 29.14% | (81 / 278) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/reporters/ | 29.75% | (72 / 242) | 18.03% | (22 / 122) | 6.87% | (9 / 131) | 31.05% | (68 / 219) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/reporters/console/ | 17.11% | (51 / 298) | 3.45% | (5 / 145) | 3.39% | (2 / 59) | 17.18% | (50 / 291) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/reporters/lang/ | 100% | (3 / 3) | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (3 / 3) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/resolvers/ | 13.33% | (2 / 15) | 100% | (0 / 0) | 0% | (0 / 3) | 13.33% | (2 / 15) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/resolvers/exotics/ | 32.3% | (125 / 387) | 18.52% | (45 / 243) | 20.45% | (18 / 88) | 33.05% | (116 / 351) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/resolvers/registries/ | 29.33% | (44 / 150) | 12.3% | (15 / 122) | 23.08% | (6 / 26) | 29.71% | (41 / 138) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/util/ | 27.2% | (358 / 1316) | 12.64% | (104 / 823) | 12.56% | (25 / 199) | 27.47% | (347 / 1263) | |
| node-npmtest-yarn/node_modules/yarn/lib-legacy/util/normalize-manifest/ | 16.59% | (34 / 205) | 2.28% | (5 / 219) | 10% | (2 / 20) | 17.01% | (33 / 194) | |
| node-npmtest-yarn/node_modules/yarn/lib/ | 75.25% | (1219 / 1620) | 56.15% | (502 / 894) | 80.95% | (204 / 252) | 76.69% | (1201 / 1566) | |
| node-npmtest-yarn/node_modules/yarn/lib/cli/ | 54.55% | (144 / 264) | 39.33% | (70 / 178) | 58.82% | (10 / 17) | 56% | (140 / 250) | |
| node-npmtest-yarn/node_modules/yarn/lib/cli/commands/ | 36.06% | (1282 / 3555) | 19.19% | (404 / 2105) | 27.96% | (177 / 633) | 37.06% | (1245 / 3359) | |
| node-npmtest-yarn/node_modules/yarn/lib/fetchers/ | 54.46% | (165 / 303) | 33.68% | (65 / 193) | 50% | (30 / 60) | 59.54% | (156 / 262) | |
| node-npmtest-yarn/node_modules/yarn/lib/lockfile/ | 79.08% | (121 / 153) | 62.6% | (77 / 123) | 78.57% | (22 / 28) | 82.52% | (118 / 143) | |
| node-npmtest-yarn/node_modules/yarn/lib/registries/ | 69.53% | (194 / 279) | 51.7% | (91 / 176) | 69.49% | (41 / 59) | 73.05% | (187 / 256) | |
| node-npmtest-yarn/node_modules/yarn/lib/reporters/ | 63.04% | (87 / 138) | 46.25% | (37 / 80) | 33.87% | (21 / 62) | 65.35% | (83 / 127) | |
| node-npmtest-yarn/node_modules/yarn/lib/reporters/console/ | 45.17% | (117 / 259) | 29.75% | (36 / 121) | 56.6% | (30 / 53) | 45.45% | (115 / 253) | |
| node-npmtest-yarn/node_modules/yarn/lib/reporters/lang/ | 100% | (11 / 11) | 83.33% | (5 / 6) | 100% | (2 / 2) | 100% | (10 / 10) | |
| node-npmtest-yarn/node_modules/yarn/lib/resolvers/ | 90.91% | (60 / 66) | 88.24% | (30 / 34) | 87.5% | (14 / 16) | 90.77% | (59 / 65) | |
| node-npmtest-yarn/node_modules/yarn/lib/resolvers/exotics/ | 48.38% | (239 / 494) | 29.39% | (92 / 313) | 43.4% | (46 / 106) | 51.23% | (229 / 447) | |
| node-npmtest-yarn/node_modules/yarn/lib/resolvers/registries/ | 50.69% | (73 / 144) | 32.14% | (36 / 112) | 70.83% | (17 / 24) | 53.03% | (70 / 132) | |
| node-npmtest-yarn/node_modules/yarn/lib/util/ | 62.99% | (885 / 1405) | 46.81% | (396 / 846) | 61.29% | (133 / 217) | 64.22% | (867 / 1350) | |
| node-npmtest-yarn/node_modules/yarn/lib/util/normalize-manifest/ | 82.25% | (315 / 383) | 67.88% | (243 / 358) | 88.1% | (37 / 42) | 83.74% | (309 / 369) |
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| example.js | 100% | (83 / 83) | 100% | (73 / 73) | 100% | (12 / 12) | 100% | (83 / 83) | |
| lib.npmtest_yarn.js | 100% | (16 / 16) | 100% | (14 / 14) | 100% | (3 / 3) | 100% | (16 / 16) | |
| test.js | 100% | (54 / 54) | 100% | (39 / 39) | 100% | (13 / 13) | 100% | (54 / 54) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | 2 2 2 2 2 2 2 1 2 2 2 2 1 2 2 2 2 2 1 2 1 1 1 1 1 1 1 1 1 2 1 1 1 1 2 2 3 3 3 3 1 3 3 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 6 6 1 2 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | /*
example.js
quickstart example
instruction
1. save this script as example.js
2. run the shell command:
$ npm install npmtest-yarn && PORT=8081 node example.js
3. play with the browser-demo on http://127.0.0.1:8081
*/
/* istanbul instrument in package npmtest_yarn */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - init-before
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || (local.modeJs === 'browser'
? local.global.utility2_npmtest_yarn
: global.utility2_moduleExports);
// export local
local.global.local = local;
}());
switch (local.modeJs) {
// init-after
// run browser js-env code - init-after
/* istanbul ignore next */
case 'browser':
local.testRunBrowser = function (event) {
Eif (!event || (event &&
event.currentTarget &&
event.currentTarget.className &&
event.currentTarget.className.includes &&
event.currentTarget.className.includes('onreset'))) {
// reset output
Array.from(
document.querySelectorAll('body > .resettable')
).forEach(function (element) {
switch (element.tagName) {
case 'INPUT':
case 'TEXTAREA':
element.value = '';
break;
default:
element.textContent = '';
}
});
}
switch (event && event.currentTarget && event.currentTarget.id) {
case 'testRunButton1':
// show tests
Eif (document.querySelector('#testReportDiv1').style.display === 'none') {
document.querySelector('#testReportDiv1').style.display = 'block';
document.querySelector('#testRunButton1').textContent =
'hide internal test';
local.modeTest = true;
local.testRunDefault(local);
// hide tests
} else {
document.querySelector('#testReportDiv1').style.display = 'none';
document.querySelector('#testRunButton1').textContent = 'run internal test';
}
break;
// custom-case
default:
break;
}
Iif (document.querySelector('#inputTextareaEval1') && (!event || (event &&
event.currentTarget &&
event.currentTarget.className &&
event.currentTarget.className.includes &&
event.currentTarget.className.includes('oneval')))) {
// try to eval input-code
try {
/*jslint evil: true*/
eval(document.querySelector('#inputTextareaEval1').value);
} catch (errorCaught) {
console.error(errorCaught);
}
}
};
// log stderr and stdout to #outputTextareaStdout1
['error', 'log'].forEach(function (key) {
console[key + '_original'] = console[key];
console[key] = function () {
var element;
console[key + '_original'].apply(console, arguments);
element = document.querySelector('#outputTextareaStdout1');
Iif (!element) {
return;
}
// append text to #outputTextareaStdout1
element.value += Array.from(arguments).map(function (arg) {
return typeof arg === 'string'
? arg
: JSON.stringify(arg, null, 4);
}).join(' ') + '\n';
// scroll textarea to bottom
element.scrollTop = element.scrollHeight;
};
});
// init event-handling
['change', 'click', 'keyup'].forEach(function (event) {
Array.from(document.querySelectorAll('.on' + event)).forEach(function (element) {
element.addEventListener(event, local.testRunBrowser);
});
});
// run tests
local.testRunBrowser();
break;
// run node js-env code - init-after
/* istanbul ignore next */
case 'node':
// export local
module.exports = local;
// require modules
local.fs = require('fs');
local.http = require('http');
local.url = require('url');
// init assets
local.assetsDict = local.assetsDict || {};
/* jslint-ignore-begin */
local.assetsDict['/assets.index.template.html'] = '\
<!doctype html>\n\
<html lang="en">\n\
<head>\n\
<meta charset="UTF-8">\n\
<meta name="viewport" content="width=device-width, initial-scale=1">\n\
<title>{{env.npm_package_name}} (v{{env.npm_package_version}})</title>\n\
<style>\n\
/*csslint\n\
box-sizing: false,\n\
universal-selector: false\n\
*/\n\
* {\n\
box-sizing: border-box;\n\
}\n\
body {\n\
background: #dde;\n\
font-family: Arial, Helvetica, sans-serif;\n\
margin: 2rem;\n\
}\n\
body > * {\n\
margin-bottom: 1rem;\n\
}\n\
.utility2FooterDiv {\n\
margin-top: 20px;\n\
text-align: center;\n\
}\n\
</style>\n\
<style>\n\
/*csslint\n\
*/\n\
textarea {\n\
font-family: monospace;\n\
height: 10rem;\n\
width: 100%;\n\
}\n\
textarea[readonly] {\n\
background: #ddd;\n\
}\n\
</style>\n\
</head>\n\
<body>\n\
<!-- utility2-comment\n\
<div id="ajaxProgressDiv1" style="background: #d00; height: 2px; left: 0; margin: 0; padding: 0; position: fixed; top: 0; transition: background 0.5s, width 1.5s; width: 25%;"></div>\n\
utility2-comment -->\n\
<h1>\n\
<!-- utility2-comment\n\
<a\n\
{{#if env.npm_package_homepage}}\n\
href="{{env.npm_package_homepage}}"\n\
{{/if env.npm_package_homepage}}\n\
target="_blank"\n\
>\n\
utility2-comment -->\n\
{{env.npm_package_name}} (v{{env.npm_package_version}})\n\
<!-- utility2-comment\n\
</a>\n\
utility2-comment -->\n\
</h1>\n\
<h3>{{env.npm_package_description}}</h3>\n\
<!-- utility2-comment\n\
<h4><a download href="assets.app.js">download standalone app</a></h4>\n\
<button class="onclick onreset" id="testRunButton1">run internal test</button><br>\n\
<div id="testReportDiv1" style="display: none;"></div>\n\
utility2-comment -->\n\
\n\
\n\
\n\
<label>stderr and stdout</label>\n\
<textarea class="resettable" id="outputTextareaStdout1" readonly></textarea>\n\
<!-- utility2-comment\n\
{{#if isRollup}}\n\
<script src="assets.app.js"></script>\n\
{{#unless isRollup}}\n\
utility2-comment -->\n\
<script src="assets.utility2.rollup.js"></script>\n\
<script src="jsonp.utility2._stateInit?callback=window.utility2._stateInit"></script>\n\
<script src="assets.npmtest_yarn.rollup.js"></script>\n\
<script src="assets.example.js"></script>\n\
<script src="assets.test.js"></script>\n\
<!-- utility2-comment\n\
{{/if isRollup}}\n\
utility2-comment -->\n\
<div class="utility2FooterDiv">\n\
[ this app was created with\n\
<a href="https://github.com/kaizhu256/node-utility2" target="_blank">utility2</a>\n\
]\n\
</div>\n\
</body>\n\
</html>\n\
';
/* jslint-ignore-end */
Iif (local.templateRender) {
local.assetsDict['/'] = local.templateRender(
local.assetsDict['/assets.index.template.html'],
{
env: local.objectSetDefault(local.env, {
npm_package_description: 'the greatest app in the world!',
npm_package_name: 'my-app',
npm_package_nameAlias: 'my_app',
npm_package_version: '0.0.1'
})
}
);
} else {
local.assetsDict['/'] = local.assetsDict['/assets.index.template.html']
.replace((/\{\{env\.(\w+?)\}\}/g), function (match0, match1) {
// jslint-hack
String(match0);
switch (match1) {
case 'npm_package_description':
return 'the greatest app in the world!';
case 'npm_package_name':
return 'my-app';
case 'npm_package_nameAlias':
return 'my_app';
case 'npm_package_version':
return '0.0.1';
}
});
}
// run the cli
Eif (local.global.utility2_rollup || module !== require.main) {
break;
}
local.assetsDict['/assets.example.js'] =
local.assetsDict['/assets.example.js'] ||
local.fs.readFileSync(__filename, 'utf8');
// bug-workaround - long $npm_package_buildCustomOrg
/* jslint-ignore-begin */
local.assetsDict['/assets.npmtest_yarn.rollup.js'] =
local.assetsDict['/assets.npmtest_yarn.rollup.js'] ||
local.fs.readFileSync(
local.npmtest_yarn.__dirname + '/lib.npmtest_yarn.js',
'utf8'
).replace((/^#!/), '//');
/* jslint-ignore-end */
local.assetsDict['/favicon.ico'] = local.assetsDict['/favicon.ico'] || '';
// if $npm_config_timeout_exit exists,
// then exit this process after $npm_config_timeout_exit ms
if (Number(process.env.npm_config_timeout_exit)) {
setTimeout(process.exit, Number(process.env.npm_config_timeout_exit));
}
// start server
if (local.global.utility2_serverHttp1) {
break;
}
process.env.PORT = process.env.PORT || '8081';
console.error('server starting on port ' + process.env.PORT);
local.http.createServer(function (request, response) {
request.urlParsed = local.url.parse(request.url);
if (local.assetsDict[request.urlParsed.pathname] !== undefined) {
response.end(local.assetsDict[request.urlParsed.pathname]);
return;
}
response.statusCode = 404;
response.end();
}).listen(process.env.PORT);
break;
}
}());
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 2 2 2 2 2 2 2 1 2 2 2 2 1 1 1 1 | /* istanbul instrument in package npmtest_yarn */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - init-before
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || local;
// init lib
local.local = local.npmtest_yarn = local;
// init exports
if (local.modeJs === 'browser') {
local.global.utility2_npmtest_yarn = local;
} else {
module.exports = local;
module.exports.__dirname = __dirname;
module.exports.module = module;
}
}());
}());
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | 2 2 2 2 2 2 2 1 2 2 1 1 1 1 2 2 2 2 1 1 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 2 2 1 2 2 1 2 2 1 1 1 1 1 | /* istanbul instrument in package npmtest_yarn */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - init-before
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
switch (local.modeJs) {
// re-init local from window.local
case 'browser':
local = local.global.utility2.objectSetDefault(
local.global.utility2_rollup || local.global.local,
local.global.utility2
);
break;
// re-init local from example.js
case 'node':
local = (local.global.utility2_rollup || require('utility2'))
.requireReadme();
break;
}
// export local
local.global.local = local;
}());
// run shared js-env code - function
(function () {
return;
}());
switch (local.modeJs) {
// run browser js-env code - function
case 'browser':
break;
// run node js-env code - function
case 'node':
break;
}
// run shared js-env code - init-after
(function () {
return;
}());
switch (local.modeJs) {
// run browser js-env code - init-after
case 'browser':
local.testCase_browser_nullCase = local.testCase_browser_nullCase || function (
options,
onError
) {
/*
* this function will test browsers's null-case handling-behavior-behavior
*/
onError(null, options);
};
// run tests
local.nop(local.modeTest &&
document.querySelector('#testRunButton1') &&
document.querySelector('#testRunButton1').click());
break;
// run node js-env code - init-after
/* istanbul ignore next */
case 'node':
local.testCase_buildApidoc_default = local.testCase_buildApidoc_default || function (
options,
onError
) {
/*
* this function will test buildApidoc's default handling-behavior-behavior
*/
options = { modulePathList: module.paths };
local.buildApidoc(options, onError);
};
local.testCase_buildApp_default = local.testCase_buildApp_default || function (
options,
onError
) {
/*
* this function will test buildApp's default handling-behavior-behavior
*/
local.testCase_buildReadme_default(options, local.onErrorThrow);
local.testCase_buildLib_default(options, local.onErrorThrow);
local.testCase_buildTest_default(options, local.onErrorThrow);
local.testCase_buildCustomOrg_default(options, local.onErrorThrow);
options = [];
local.buildApp(options, onError);
};
local.testCase_buildCustomOrg_default = local.testCase_buildCustomOrg_default ||
function (options, onError) {
/*
* this function will test buildCustomOrg's default handling-behavior
*/
options = {};
local.buildCustomOrg(options, onError);
};
local.testCase_buildLib_default = local.testCase_buildLib_default || function (
options,
onError
) {
/*
* this function will test buildLib's default handling-behavior
*/
options = {};
local.buildLib(options, onError);
};
local.testCase_buildReadme_default = local.testCase_buildReadme_default || function (
options,
onError
) {
/*
* this function will test buildReadme's default handling-behavior-behavior
*/
options = {};
local.buildReadme(options, onError);
};
local.testCase_buildTest_default = local.testCase_buildTest_default || function (
options,
onError
) {
/*
* this function will test buildTest's default handling-behavior
*/
options = {};
local.buildTest(options, onError);
};
local.testCase_webpage_default = local.testCase_webpage_default || function (
options,
onError
) {
/*
* this function will test webpage's default handling-behavior
*/
options = { modeCoverageMerge: true, url: local.serverLocalHost + '?modeTest=1' };
local.browserTest(options, onError);
};
// run test-server
local.testRunServer(local);
break;
}
}());
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| yarn.js | 79.17% | (19 / 24) | 50% | (5 / 10) | 100% | (0 / 0) | 79.17% | (19 / 24) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | //#!/usr/bin/env node
/* eslint-disable no-var */
/* eslint-disable flowtype/require-valid-file-annotation */
'use strict';
// validate that used node version is supported
var semver = require('semver');
var ver = process.versions.node;
ver = ver.split('-')[0]; // explode and truncate tag from version #511
var path = null;
Eif (semver.satisfies(ver, '>=5.0.0')) {
path = '../lib/cli/index.js';
} else if (semver.satisfies(ver, '>=4.0.0')) {
path = '../lib-legacy/cli/index.js';
} else {
console.log(require('chalk').red('Node version ' + ver + ' is not supported, please use Node.js 4.0 or higher.'));
process.exit(1);
}
// load v8-compile-cache
Eif (semver.satisfies(ver, '>=5.7.0')) {
require('v8-compile-cache');
}
// ensure cache directory exists
var mkdirp = require('mkdirp');
var constants = require('../lib-legacy/constants');
mkdirp.sync(constants.MODULE_CACHE_DIRECTORY);
// init roadrunner
var YARN_VERSION = require('../package.json').version;
var roadrunner = require('roadrunner');
// load cache
roadrunner.load(constants.CACHE_FILENAME);
var cacheVersion = roadrunner.get('CACHE_BREAKER').version;
Iif (!cacheVersion || cacheVersion !== YARN_VERSION) {
// reset cache if it's for an older yarn
roadrunner.reset(constants.CACHE_FILENAME);
}
// set this cache to the current yarn version
roadrunner.set('CACHE_BREAKER', {version: YARN_VERSION});
// save cache on SIGINT
roadrunner.setup(constants.CACHE_FILENAME);
module.exports = require(path);
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| constants.js | 87.27% | (48 / 55) | 50% | (7 / 14) | 100% | (5 / 5) | 87.27% | (48 / 55) | |
| package-compatibility.js | 25% | (24 / 96) | 10.94% | (7 / 64) | 23.08% | (3 / 13) | 24.21% | (23 / 95) | |
| package-constraint-resolver.js | 46.15% | (6 / 13) | 0% | (0 / 10) | 0% | (0 / 4) | 50% | (6 / 12) | |
| package-fetcher.js | 17.28% | (14 / 81) | 0% | (0 / 48) | 0% | (0 / 18) | 19.72% | (14 / 71) | |
| package-hoister.js | 6.62% | (18 / 272) | 0% | (0 / 121) | 0% | (0 / 22) | 6.64% | (18 / 271) | |
| package-install-scripts.js | 13.71% | (27 / 197) | 0% | (0 / 104) | 0% | (0 / 30) | 14.44% | (27 / 187) | |
| package-linker.js | 18.45% | (43 / 233) | 5.95% | (10 / 168) | 9.09% | (4 / 44) | 17.94% | (40 / 223) | |
| package-reference.js | 13.21% | (7 / 53) | 0% | (0 / 20) | 0% | (0 / 13) | 13.46% | (7 / 52) | |
| package-request.js | 16.06% | (35 / 218) | 0% | (0 / 115) | 0% | (0 / 43) | 16.83% | (35 / 208) | |
| package-resolver.js | 10.14% | (21 / 207) | 0% | (0 / 79) | 0% | (0 / 33) | 10.19% | (21 / 206) | |
| types.js | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (0 / 0) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getPathKey = getPathKey;
exports.isRootUser = isRootUser;
const path = require('path');
const userHome = require('./util/user-home-dir').default;
const DEPENDENCY_TYPES = exports.DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies'];
const YARN_REGISTRY = exports.YARN_REGISTRY = 'https://registry.yarnpkg.com';
const YARN_DOCS = exports.YARN_DOCS = 'https://yarnpkg.com/en/docs/cli/';
const YARN_INSTALLER_SH = exports.YARN_INSTALLER_SH = 'https://yarnpkg.com/install.sh';
const YARN_INSTALLER_MSI = exports.YARN_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi';
const SELF_UPDATE_VERSION_URL = exports.SELF_UPDATE_VERSION_URL = 'https://yarnpkg.com/latest-version';
const SELF_UPDATE_TARBALL_URL = exports.SELF_UPDATE_TARBALL_URL = 'https://yarnpkg.com/latest.tar.gz';
const SELF_UPDATE_DOWNLOAD_FOLDER = exports.SELF_UPDATE_DOWNLOAD_FOLDER = 'updates';
// cache version, bump whenever we make backwards incompatible changes
const CACHE_VERSION = exports.CACHE_VERSION = 1;
// lockfile version, bump whenever we make backwards incompatible changes
const LOCKFILE_VERSION = exports.LOCKFILE_VERSION = 1;
// max amount of network requests to perform concurrently
const NETWORK_CONCURRENCY = exports.NETWORK_CONCURRENCY = 8;
// max amount of child processes to execute concurrently
const CHILD_CONCURRENCY = exports.CHILD_CONCURRENCY = 5;
const REQUIRED_PACKAGE_KEYS = exports.REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid'];
function getDirectory(category) {
// use %LOCALAPPDATA%/Yarn on Windows
Iif (process.platform === 'win32' && process.env.LOCALAPPDATA) {
return path.join(process.env.LOCALAPPDATA, 'Yarn', category);
}
// otherwise use ~/.{category}/yarn
return path.join(userHome, `.${category}`, 'yarn');
}
function getCacheDirectory() {
Iif (process.platform === 'darwin') {
return path.join(userHome, 'Library', 'Caches', 'Yarn');
}
return getDirectory('cache');
}
const MODULE_CACHE_DIRECTORY = exports.MODULE_CACHE_DIRECTORY = getCacheDirectory();
const CONFIG_DIRECTORY = exports.CONFIG_DIRECTORY = getDirectory('config');
const LINK_REGISTRY_DIRECTORY = exports.LINK_REGISTRY_DIRECTORY = path.join(CONFIG_DIRECTORY, 'link');
const GLOBAL_MODULE_DIRECTORY = exports.GLOBAL_MODULE_DIRECTORY = path.join(CONFIG_DIRECTORY, 'global');
const CACHE_FILENAME = exports.CACHE_FILENAME = path.join(MODULE_CACHE_DIRECTORY, '.roadrunner.json');
const INTEGRITY_FILENAME = exports.INTEGRITY_FILENAME = '.yarn-integrity';
const LOCKFILE_FILENAME = exports.LOCKFILE_FILENAME = 'yarn.lock';
const METADATA_FILENAME = exports.METADATA_FILENAME = '.yarn-metadata.json';
const TARBALL_FILENAME = exports.TARBALL_FILENAME = '.yarn-tarball.tgz';
const CLEAN_FILENAME = exports.CLEAN_FILENAME = '.yarnclean';
const DEFAULT_INDENT = exports.DEFAULT_INDENT = ' ';
const SINGLE_INSTANCE_PORT = exports.SINGLE_INSTANCE_PORT = 31997;
const SINGLE_INSTANCE_FILENAME = exports.SINGLE_INSTANCE_FILENAME = '.yarn-single-instance';
const ENV_PATH_KEY = exports.ENV_PATH_KEY = getPathKey(process.platform, process.env);
function getPathKey(platform, env) {
let pathKey = 'PATH';
// windows calls its path "Path" usually, but this is not guaranteed.
Iif (platform === 'win32') {
pathKey = 'Path';
for (const key in env) {
if (key.toLowerCase() === 'path') {
pathKey = key;
}
}
}
return pathKey;
}
function getUid() {
Eif (process.platform !== 'win32' && process.getuid) {
return process.getuid();
}
return null;
}
const ROOT_USER = exports.ROOT_USER = isRootUser(getUid());
function isRootUser(uid) {
return uid === 0;
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _assign;
function _load_assign() {
return _assign = _interopRequireDefault(require('babel-runtime/core-js/object/assign'));
}
exports.testEngine = testEngine;
var _errors;
function _load_errors() {
return _errors = require('./errors.js');
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('./util/map.js'));
}
var _misc;
function _load_misc() {
return _misc = require('./util/misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const semver = require('semver');
const VERSIONS = (0, (_assign || _load_assign()).default)({}, process.versions, {
yarn: require('../package.json').version
});
function isValid(items, actual) {
let isNotWhitelist = true;
let isBlacklist = false;
for (const item of items) {
// blacklist
if (item[0] === '!') {
isBlacklist = true;
if (actual === item.slice(1)) {
return false;
}
// whitelist
} else {
isNotWhitelist = false;
if (item === actual) {
return true;
}
}
}
// npm allows blacklists and whitelists to be mixed. Blacklists with
// whitelisted items should be treated as whitelists.
return isBlacklist && isNotWhitelist;
}
const aliases = (0, (_map || _load_map()).default)({
iojs: 'node' });
const ignore = ['npm', // we'll never satisfy this for obvious reasons
'teleport', // a module bundler used by some modules
'rhino'];
function testEngine(name, range, versions, looseSemver) {
const actual = versions[name];
if (!actual) {
return false;
}
if (!semver.valid(actual, looseSemver)) {
return false;
}
if (semver.satisfies(actual, range, looseSemver)) {
return true;
}
if (name === 'node' && semver.gt(actual, '1.0.0', looseSemver)) {
// WARNING: this is a massive hack and is super gross but necessary for compatibility
// some modules have the `engines.node` field set to a caret version below semver major v1
// eg. ^0.12.0. this is problematic as we enforce engines checks and node is now on version >=1
// to allow this pattern we transform the node version to fake ones in the minor range 10-13
const major = semver.major(actual, looseSemver);
const fakes = [`0.10.${major}`, `0.11.${major}`, `0.12.${major}`, `0.13.${major}`];
for (const actualFake of fakes) {
if (semver.satisfies(actualFake, range, looseSemver)) {
return true;
}
}
}
// incompatible version
return false;
}
class PackageCompatibility {
constructor(config, resolver, ignoreEngines) {
this.reporter = config.reporter;
this.resolver = resolver;
this.config = config;
this.ignoreEngines = ignoreEngines;
}
static isValidArch(archs) {
return isValid(archs, process.arch);
}
static isValidPlatform(platforms) {
return isValid(platforms, process.platform);
}
check(info) {
let didIgnore = false;
let didError = false;
const reporter = this.reporter;
const human = `${info.name}@${info.version}`;
const pushError = msg => {
const ref = info._reference;
invariant(ref, 'expected package reference');
if (ref.optional) {
ref.ignore = true;
reporter.warn(`${human}: ${msg}`);
if (!didIgnore) {
reporter.info(reporter.lang('optionalCompatibilityExcluded', human));
didIgnore = true;
}
} else {
reporter.error(`${human}: ${msg}`);
didError = true;
}
};
const invalidPlatform = !this.config.ignorePlatform && Array.isArray(info.os) && info.os.length > 0 && !PackageCompatibility.isValidPlatform(info.os);
if (invalidPlatform) {
pushError(this.reporter.lang('incompatibleOS', process.platform));
}
const invalidCpu = !this.config.ignorePlatform && Array.isArray(info.cpu) && info.cpu.length > 0 && !PackageCompatibility.isValidArch(info.cpu);
if (invalidCpu) {
pushError(this.reporter.lang('incompatibleCPU', process.arch));
}
if (!this.ignoreEngines && typeof info.engines === 'object') {
for (const entry of (0, (_misc || _load_misc()).entries)(info.engines)) {
let name = entry[0];
const range = entry[1];
if (aliases[name]) {
name = aliases[name];
}
if (VERSIONS[name]) {
if (!testEngine(name, range, VERSIONS, this.config.looseSemver)) {
pushError(this.reporter.lang('incompatibleEngine', name, range));
}
} else if (ignore.indexOf(name) < 0) {
this.reporter.warn(`${human}: ${this.reporter.lang('invalidEngine', name)}`);
}
}
}
if (didError) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('foundIncompatible'));
}
}
init() {
const infos = this.resolver.getManifests();
for (const info of infos) {
this.check(info);
}
return (_promise || _load_promise()).default.resolve();
}
}
exports.default = PackageCompatibility;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const semver = require('semver');
// This isn't really a "proper" constraint resolver. We just return the highest semver
// version in the versions passed that satisfies the input range. This vastly reduces
// the complexity and is very efficient for package resolution.
class PackageConstraintResolver {
constructor(config, reporter) {
this.reporter = reporter;
this.config = config;
}
reduce(versions, range) {
if (range === 'latest') {
// Usually versions are already ordered and the last one is the latest
return (_promise || _load_promise()).default.resolve(versions[versions.length - 1]);
} else {
return (_promise || _load_promise()).default.resolve(semver.maxSatisfying(versions, range, this.config.looseSemver));
}
}
}
exports.default = PackageConstraintResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _errors;
function _load_errors() {
return _errors = require('./errors.js');
}
var _index;
function _load_index() {
return _index = _interopRequireWildcard(require('./fetchers/index.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('./util/fs.js'));
}
var _promise;
function _load_promise() {
return _promise = _interopRequireWildcard(require('./util/promise.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class PackageFetcher {
constructor(config, resolver) {
this.reporter = config.reporter;
this.resolver = resolver;
this.config = config;
}
fetchCache(dest, fetcher) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
var _ref = yield _this.config.readPackageMetadata(dest);
const hash = _ref.hash,
pkg = _ref.package;
return {
package: pkg,
resolved: yield fetcher.getResolvedFromCached(hash),
hash: hash,
dest: dest,
cached: true
};
})();
}
fetch(ref) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const dest = _this2.config.generateHardModulePath(ref);
const remote = ref.remote;
const Fetcher = (_index || _load_index())[remote.type];
if (!Fetcher) {
throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('unknownFetcherFor', remote.type));
}
const fetcher = new Fetcher(dest, remote, _this2.config);
if (yield _this2.config.isValidModuleDest(dest)) {
return _this2.fetchCache(dest, fetcher);
}
// remove as the module may be invalid
yield (_fs || _load_fs()).unlink(dest);
try {
return yield fetcher.fetch();
} catch (err) {
try {
yield (_fs || _load_fs()).unlink(dest);
} catch (err2) {
// what do?
}
throw err;
}
})();
}
maybeFetch(ref) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
try {
return yield _this3.fetch(ref);
} catch (err) {
if (ref.optional) {
_this3.reporter.error(err.message);
return null;
} else {
throw err;
}
}
})();
}
init() {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const pkgs = _this4.resolver.getPackageReferences();
const tick = _this4.reporter.progress(pkgs.length);
yield (_promise || _load_promise()).queue(pkgs, (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (ref) {
const res = yield _this4.maybeFetch(ref);
let newPkg;
if (res) {
newPkg = res.package;
// update with new remote
// but only if there was a hash previously as the tarball fetcher does not provide a hash.
if (ref.remote.hash) {
ref.remote.hash = res.hash;
}
if (res.resolved) {
ref.remote.resolved = res.resolved;
}
}
if (newPkg) {
// update with fresh manifest
yield _this4.resolver.updateManifest(ref, newPkg);
}
if (tick) {
tick(ref.name);
}
});
return function (_x) {
return _ref2.apply(this, arguments);
};
})(), _this4.config.networkConcurrency);
})();
}
}
exports.default = PackageFetcher;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.HoistManifest = undefined;
var _keys;
function _load_keys() {
return _keys = _interopRequireDefault(require('babel-runtime/core-js/object/keys'));
}
var _set;
function _load_set() {
return _set = _interopRequireDefault(require('babel-runtime/core-js/set'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('babel-runtime/core-js/map'));
}
var _misc;
function _load_misc() {
return _misc = require('./util/misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const path = require('path');
let historyCounter = 0;
class HoistManifest {
constructor(key, parts, pkg, loc, isIgnored, inheritIsIgnored) {
this.isIgnored = isIgnored;
this.inheritIsIgnored = inheritIsIgnored;
this.loc = loc;
this.pkg = pkg;
this.key = key;
this.parts = parts;
this.originalKey = key;
this.previousKeys = [];
this.history = [];
this.addHistory(`Start position = ${key}`);
}
addHistory(msg) {
this.history.push(`${++historyCounter}: ${msg}`);
}
}
exports.HoistManifest = HoistManifest;
class PackageHoister {
constructor(config, resolver) {
this.resolver = resolver;
this.config = config;
this.taintedKeys = new (_map || _load_map()).default();
this.levelQueue = [];
this.tree = new (_map || _load_map()).default();
}
/**
* Taint this key and prevent any modules from being hoisted to it.
*/
taintKey(key, info) {
const existingTaint = this.taintedKeys.get(key);
if (existingTaint && existingTaint.loc !== info.loc) {
return false;
} else {
this.taintedKeys.set(key, info);
return true;
}
}
/**
* Implode an array of ancestry parts into a key.
*/
implodeKey(parts) {
return parts.join('#');
}
/**
* Seed the hoister with patterns taken from the included resolver.
*/
seed(patterns) {
this.prepass(patterns);
for (const pattern of this.resolver.dedupePatterns(patterns)) {
this._seed(pattern);
}
while (true) {
let queue = this.levelQueue;
if (!queue.length) {
this._propagateNonIgnored();
return;
}
this.levelQueue = [];
// sort queue to get determinism between runs
queue = queue.sort((_ref, _ref2) => {
var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 1);
let aPattern = _ref4[0];
var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 1);
let bPattern = _ref3[0];
return (0, (_misc || _load_misc()).sortAlpha)(aPattern, bPattern);
});
//
const infos = [];
for (const _ref5 of queue) {
var _ref6 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref5, 2);
const pattern = _ref6[0];
const parents = _ref6[1];
const info = this._seed(pattern, parents);
if (info) {
infos.push(info);
}
}
//
for (const info of infos) {
this.hoist(info);
}
}
}
/**
* Seed the hoister with a specific pattern.
*/
_seed(pattern, parent) {
//
const pkg = this.resolver.getStrictResolvedPattern(pattern);
const ref = pkg._reference;
invariant(ref, 'expected reference');
//
let parentParts = [];
let isIgnored = ref.ignore;
let inheritIsIgnored = false;
if (parent) {
if (!this.tree.get(parent.key)) {
return null;
}
// non ignored dependencies inherit parent's ignored status
// parent may transition from ignored to non ignored when hoisted if it is used in another non ignored branch
if (!isIgnored && parent.isIgnored) {
isIgnored = parent.isIgnored;
inheritIsIgnored = true;
}
parentParts = parent.parts;
}
//
const loc = this.config.generateHardModulePath(ref);
const parts = parentParts.concat(pkg.name);
const key = this.implodeKey(parts);
const info = new HoistManifest(key, parts, pkg, loc, isIgnored, inheritIsIgnored);
//
this.tree.set(key, info);
this.taintKey(key, info);
//
for (const depPattern of ref.dependencies) {
this.levelQueue.push([depPattern, info]);
}
return info;
}
/**
* Propagate inherited ignore statuses from non-ignored to ignored packages
*/
_propagateNonIgnored() {
//
const toVisit = [];
// enumerate all non-ignored packages
for (const entry of this.tree.entries()) {
if (!entry[1].isIgnored) {
toVisit.push(entry[1]);
}
}
// visit them
while (toVisit.length) {
const info = toVisit.shift();
const ref = info.pkg._reference;
invariant(ref, 'expected reference');
for (const depPattern of ref.dependencies) {
const depinfo = this._lookupDependency(info, depPattern);
if (depinfo && depinfo.isIgnored && depinfo.inheritIsIgnored) {
depinfo.isIgnored = false;
info.addHistory(`Mark as non-ignored because of usage by ${info.key}`);
toVisit.push(depinfo);
}
}
}
}
/**
* Looks up the package a dependency resolves to
*/
_lookupDependency(info, depPattern) {
//
const pkg = this.resolver.getStrictResolvedPattern(depPattern);
const ref = pkg._reference;
invariant(ref, 'expected reference');
//
for (let i = info.parts.length; i >= 0; i--) {
const checkParts = info.parts.slice(0, i).concat(pkg.name);
const checkKey = this.implodeKey(checkParts);
const existing = this.tree.get(checkKey);
if (existing) {
return existing;
}
}
return null;
}
/**
* Find the highest position we can hoist this module to.
*/
getNewParts(key, info, parts) {
let stepUp = false;
const fullKey = this.implodeKey(parts);
const stack = []; // stack of removed parts
const name = parts.pop();
//
for (let i = parts.length - 1; i >= 0; i--) {
const checkParts = parts.slice(0, i).concat(name);
const checkKey = this.implodeKey(checkParts);
info.addHistory(`Looked at ${checkKey} for a match`);
const existing = this.tree.get(checkKey);
if (existing) {
if (existing.loc === info.loc) {
// switch to non ignored if earlier deduped version was ignored
if (existing.isIgnored && !info.isIgnored) {
existing.isIgnored = info.isIgnored;
}
existing.addHistory(`Deduped ${fullKey} to this item`);
return { parts: checkParts, duplicate: true };
} else {
// everything above will be shadowed and this is a conflict
info.addHistory(`Found a collision at ${checkKey}`);
break;
}
}
const existingTaint = this.taintedKeys.get(checkKey);
if (existingTaint && existingTaint.loc !== info.loc) {
info.addHistory(`Broken by ${checkKey}`);
break;
}
}
// remove redundant parts that wont collide
while (parts.length) {
const checkParts = parts.concat(name);
const checkKey = this.implodeKey(checkParts);
//
const existing = this.tree.get(checkKey);
if (existing) {
stepUp = true;
break;
}
// check if we're trying to hoist ourselves to a previously unflattened module key,
// this will result in a conflict and we'll need to move ourselves up
if (key !== checkKey && this.taintedKeys.has(checkKey)) {
stepUp = true;
break;
}
//
stack.push(parts.pop());
}
//
parts.push(name);
//
const isValidPosition = parts => {
const key = this.implodeKey(parts);
const existing = this.tree.get(key);
if (existing && existing.loc === info.loc) {
return true;
}
// ensure there's no taint or the taint is us
const existingTaint = this.taintedKeys.get(key);
if (existingTaint && existingTaint.loc !== info.loc) {
return false;
}
return true;
};
// we need to special case when we attempt to hoist to the top level as the `existing` logic
// wont be hit in the above `while` loop and we could conflict
if (!isValidPosition(parts)) {
stepUp = true;
}
// sometimes we need to step up to a parent module to install ourselves
while (stepUp && stack.length) {
info.addHistory(`Stepping up from ${this.implodeKey(parts)}`);
parts.pop(); // remove `name`
parts.push(stack.pop(), name);
if (isValidPosition(parts)) {
info.addHistory(`Found valid position ${this.implodeKey(parts)}`);
stepUp = false;
}
}
return { parts: parts, duplicate: false };
}
/**
* Hoist all seeded patterns to their highest positions.
*/
hoist(info) {
const key = info.key,
rawParts = info.parts;
// remove this item from the `tree` map so we can ignore it
this.tree.delete(key);
var _getNewParts = this.getNewParts(key, info, rawParts.slice());
const parts = _getNewParts.parts,
duplicate = _getNewParts.duplicate;
const newKey = this.implodeKey(parts);
const oldKey = key;
if (duplicate) {
info.addHistory(`Satisfied from above by ${newKey}`);
this.declareRename(info, rawParts, parts);
return;
}
// update to the new key
if (oldKey === newKey) {
info.addHistory("Didn't hoist - conflicts above");
this.setKey(info, oldKey, parts);
return;
}
//
this.declareRename(info, rawParts, parts);
this.setKey(info, newKey, parts);
}
/**
* Declare that a module has been hoisted and update our internal references.
*/
declareRename(info, oldParts, newParts) {
// go down the tree from our new position reserving our name
this.taintParents(info, oldParts.slice(0, -1), newParts.length - 1);
}
/**
* Crawl upwards through a list of ancestry parts and taint a package name.
*/
taintParents(info, processParts, start) {
for (let i = start; i < processParts.length; i++) {
const parts = processParts.slice(0, i).concat(info.pkg.name);
const key = this.implodeKey(parts);
if (this.taintKey(key, info)) {
info.addHistory(`Tainted ${key} to prevent collisions`);
}
}
}
/**
* Update the key of a module and update our references.
*/
setKey(info, newKey, parts) {
const oldKey = info.key;
info.key = newKey;
info.parts = parts;
this.tree.set(newKey, info);
if (oldKey === newKey) {
return;
}
info.previousKeys.push(newKey);
info.addHistory(`New position = ${newKey}`);
}
/**
* Perform a prepass and if there's multiple versions of the same package, hoist the one with
* the most dependents to the top.
*/
prepass(patterns) {
patterns = this.resolver.dedupePatterns(patterns).sort();
const occurences = {};
// add an occuring package to the above data structure
const add = (pattern, ancestry) => {
const pkg = this.resolver.getStrictResolvedPattern(pattern);
if (ancestry.indexOf(pkg) >= 0) {
// prevent recursive dependencies
return;
}
const ref = pkg._reference;
invariant(ref, 'expected reference');
const versions = occurences[pkg.name] = occurences[pkg.name] || {};
const version = versions[pkg.version] = versions[pkg.version] || { occurences: new (_set || _load_set()).default(), pattern: pattern };
version.occurences.add(ancestry[ancestry.length - 1]);
for (const depPattern of ref.dependencies) {
add(depPattern, ancestry.concat(pkg));
}
};
// get a list of root package names since we can't hoist other dependencies to these spots!
const rootPackageNames = new (_set || _load_set()).default();
for (const pattern of patterns) {
const pkg = this.resolver.getStrictResolvedPattern(pattern);
rootPackageNames.add(pkg.name);
}
// seed occurences
for (const pattern of patterns) {
add(pattern, []);
}
for (const packageName of (0, (_keys || _load_keys()).default)(occurences).sort()) {
const versionOccurences = occurences[packageName];
const versions = (0, (_keys || _load_keys()).default)(versionOccurences);
if (versions.length === 1) {
// only one package type so we'll hoist this to the top anyway
continue;
}
if (this.tree.get(packageName)) {
// a transitive dependency of a previously hoisted dependency exists
continue;
}
if (rootPackageNames.has(packageName)) {
// can't replace top level packages
continue;
}
let mostOccurenceCount;
let mostOccurencePattern;
for (const version of (0, (_keys || _load_keys()).default)(versionOccurences).sort()) {
var _versionOccurences$ve = versionOccurences[version];
const occurences = _versionOccurences$ve.occurences,
pattern = _versionOccurences$ve.pattern;
const occurenceCount = occurences.size;
if (!mostOccurenceCount || occurenceCount > mostOccurenceCount) {
mostOccurenceCount = occurenceCount;
mostOccurencePattern = pattern;
}
}
invariant(mostOccurencePattern, 'expected most occuring pattern');
invariant(mostOccurenceCount, 'expected most occuring count');
// only hoist this module if it occured more than once
if (mostOccurenceCount > 1) {
this._seed(mostOccurencePattern);
}
}
}
/**
* Produce a flattened list of module locations and manifests.
*/
init() {
const flatTree = [];
//
for (const _ref7 of this.tree.entries()) {
var _ref8 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref7, 2);
const key = _ref8[0];
const info = _ref8[1];
// decompress the location and push it to the flat tree. this path could be made
const parts = [];
const keyParts = key.split('#');
for (let i = 0; i < keyParts.length; i++) {
const key = keyParts.slice(0, i + 1).join('#');
const hoisted = this.tree.get(key);
invariant(hoisted, 'expected hoisted manifest');
parts.push(this.config.getFolder(hoisted.pkg));
parts.push(keyParts[i]);
}
if (this.config.modulesFolder) {
// remove the first part which will be the folder name and replace it with a
// hardcoded modules folder
parts.shift();
const modulesFolder = this.config.modulesFolder == null ? '' : this.config.modulesFolder;
parts.unshift(modulesFolder);
} else {
// first part will be the registry-specific module folder
const cwd = this.config.cwd == null ? '' : this.config.cwd;
parts.unshift(cwd);
}
const loc = path.join.apply(path, parts);
flatTree.push([loc, info]);
}
// remove ignored modules from the tree
const visibleFlatTree = [];
for (const _ref9 of flatTree) {
var _ref10 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref9, 2);
const loc = _ref10[0];
const info = _ref10[1];
const ref = info.pkg._reference;
invariant(ref, 'expected reference');
if (info.isIgnored) {
info.addHistory('Deleted as this module was ignored');
} else {
visibleFlatTree.push([loc, info]);
}
}
return visibleFlatTree;
}
}
exports.default = PackageHoister;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _stringify;
function _load_stringify() {
return _stringify = _interopRequireDefault(require('babel-runtime/core-js/json/stringify'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('babel-runtime/core-js/map'));
}
var _set;
function _load_set() {
return _set = _interopRequireDefault(require('babel-runtime/core-js/set'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _executeLifecycleScript;
function _load_executeLifecycleScript() {
return _executeLifecycleScript = _interopRequireDefault(require('./util/execute-lifecycle-script.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('./util/fs.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('./constants.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const path = require('path');
const INSTALL_STAGES = ['preinstall', 'install', 'postinstall'];
class PackageInstallScripts {
constructor(config, resolver, force) {
this.installed = 0;
this.resolver = resolver;
this.reporter = config.reporter;
this.config = config;
this.force = force;
}
getInstallCommands(pkg) {
const scripts = pkg.scripts;
if (scripts) {
const cmds = [];
for (const stage of INSTALL_STAGES) {
const cmd = scripts[stage];
if (cmd) {
cmds.push([stage, cmd]);
}
}
return cmds;
} else {
return [];
}
}
walk(loc) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const files = yield (_fs || _load_fs()).walk(loc, null, new (_set || _load_set()).default(_this.config.registryFolders));
const mtimes = new (_map || _load_map()).default();
for (const file of files) {
mtimes.set(file.relative, file.mtime);
}
return mtimes;
})();
}
saveBuildArtifacts(loc, pkg, beforeFiles, spinner) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const afterFiles = yield _this2.walk(loc);
// work out what files have been created/modified
const buildArtifacts = [];
for (const _ref of afterFiles) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const file = _ref2[0];
const mtime = _ref2[1];
if (!beforeFiles.has(file) || beforeFiles.get(file) !== mtime) {
buildArtifacts.push(file);
}
}
if (!buildArtifacts.length) {
// nothing else to do here since we have no build artifacts
return;
}
// if the process is killed while copying over build artifacts then we'll leave
// the cache in a bad state. remove the metadata file and add it back once we've
// done our copies to ensure cache integrity.
const cachedLoc = _this2.config.generateHardModulePath(pkg._reference, true);
const metadata = yield _this2.config.readPackageMetadata(cachedLoc);
metadata.artifacts = buildArtifacts;
const metadataLoc = path.join(cachedLoc, (_constants || _load_constants()).METADATA_FILENAME);
yield (_fs || _load_fs()).writeFile(metadataLoc, (0, (_stringify || _load_stringify()).default)((0, (_extends2 || _load_extends()).default)({}, metadata, {
// config.readPackageMetadata also returns the package manifest but that's not in the original
// metadata json
package: undefined
}), null, ' '));
})();
}
install(cmds, pkg, spinner) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const ref = pkg._reference;
invariant(ref, 'expected reference');
const loc = _this3.config.generateHardModulePath(ref);
try {
for (const _ref3 of cmds) {
var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2);
const stage = _ref4[0];
const cmd = _ref4[1];
yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).default)(stage, _this3.config, loc, cmd, spinner);
}
} catch (err) {
err.message = `${loc}: ${err.message}`;
invariant(ref, 'expected reference');
if (ref.optional) {
ref.ignore = true;
_this3.reporter.warn(_this3.reporter.lang('optionalModuleScriptFail', err.message));
_this3.reporter.info(_this3.reporter.lang('optionalModuleFail'));
// Cleanup node_modules
try {
yield (_fs || _load_fs()).unlink(loc);
} catch (e) {
_this3.reporter.error(_this3.reporter.lang('optionalModuleCleanupFail', e.message));
}
} else {
throw err;
}
}
})();
}
packageCanBeInstalled(pkg) {
const cmds = this.getInstallCommands(pkg);
if (!cmds.length) {
return false;
}
const ref = pkg._reference;
invariant(ref, 'Missing package reference');
if (!ref.fresh && !this.force) {
// this package hasn't been touched
return false;
}
// we haven't actually written this module out
if (ref.ignore) {
return false;
}
return true;
}
runCommand(spinner, pkg) {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const cmds = _this4.getInstallCommands(pkg);
spinner.setPrefix(++_this4.installed, pkg.name);
yield _this4.install(cmds, pkg, spinner);
})();
}
// detect if there is a circularDependency in the dependency tree
detectCircularDependencies(root, seenManifests, pkg) {
const ref = pkg._reference;
invariant(ref, 'expected reference');
const deps = ref.dependencies;
for (const dep of deps) {
const pkgDep = this.resolver.getStrictResolvedPattern(dep);
if (seenManifests.has(pkgDep)) {
// there is a cycle but not with the root
continue;
}
seenManifests.add(pkgDep);
// found a dependency pointing to root
if (pkgDep == root) {
return true;
}
if (this.detectCircularDependencies(root, seenManifests, pkgDep)) {
return true;
}
}
return false;
}
// find the next package to be installed
findInstallablePackage(workQueue, installed) {
for (const pkg of workQueue) {
const ref = pkg._reference;
invariant(ref, 'expected reference');
const deps = ref.dependencies;
let dependenciesFullfilled = true;
for (const dep of deps) {
const pkgDep = this.resolver.getStrictResolvedPattern(dep);
if (!installed.has(pkgDep)) {
dependenciesFullfilled = false;
break;
}
}
// all depedencies are installed
if (dependenciesFullfilled) {
return pkg;
}
// detect circular dependency, mark this pkg as installable to break the circle
if (this.detectCircularDependencies(pkg, new (_set || _load_set()).default(), pkg)) {
return pkg;
}
}
return null;
}
worker(spinner, workQueue, installed, waitQueue) {
var _this5 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
while (true) {
// No more work to be done
if (workQueue.size == 0) {
break;
}
// find a installable package
const pkg = _this5.findInstallablePackage(workQueue, installed);
// can't find a package to install, register into waitQueue
if (pkg == null) {
spinner.clear();
yield new (_promise || _load_promise()).default(function (resolve) {
return waitQueue.add(resolve);
});
continue;
}
// found a package to install
workQueue.delete(pkg);
if (_this5.packageCanBeInstalled(pkg)) {
yield _this5.runCommand(spinner, pkg);
}
installed.add(pkg);
for (const workerResolve of waitQueue) {
workerResolve();
}
waitQueue.clear();
}
})();
}
init(seedPatterns) {
var _this6 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const workQueue = new (_set || _load_set()).default();
const installed = new (_set || _load_set()).default();
const pkgs = _this6.resolver.getTopologicalManifests(seedPatterns);
let installablePkgs = 0;
// A map to keep track of what files exist before installation
const beforeFilesMap = new (_map || _load_map()).default();
for (const pkg of pkgs) {
if (_this6.packageCanBeInstalled(pkg)) {
const ref = pkg._reference;
invariant(ref, 'expected reference');
const loc = _this6.config.generateHardModulePath(ref);
beforeFilesMap.set(loc, (yield _this6.walk(loc)));
installablePkgs += 1;
}
workQueue.add(pkg);
}
// waitQueue acts like a semaphore to allow workers to register to be notified
// when there are more work added to the work queue
const waitQueue = new (_set || _load_set()).default();
const workers = [];
const set = _this6.reporter.activitySet(installablePkgs, Math.min((_constants || _load_constants()).CHILD_CONCURRENCY, workQueue.size));
for (const spinner of set.spinners) {
workers.push(_this6.worker(spinner, workQueue, installed, waitQueue));
}
yield (_promise || _load_promise()).default.all(workers);
// cache all build artifacts
for (const pkg of pkgs) {
if (_this6.packageCanBeInstalled(pkg)) {
const ref = pkg._reference;
invariant(ref, 'expected reference');
const loc = _this6.config.generateHardModulePath(ref);
const beforeFiles = beforeFilesMap.get(loc);
invariant(beforeFiles, 'files before installation should always be recorded');
yield _this6.saveBuildArtifacts(loc, pkg, beforeFiles, set.spinners[0]);
}
}
set.end();
})();
}
}
exports.default = PackageInstallScripts;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.linkBin = undefined;
var _from;
function _load_from() {
return _from = _interopRequireDefault(require('babel-runtime/core-js/array/from'));
}
var _set;
function _load_set() {
return _set = _interopRequireDefault(require('babel-runtime/core-js/set'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('babel-runtime/core-js/map'));
}
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _keys;
function _load_keys() {
return _keys = _interopRequireDefault(require('babel-runtime/core-js/object/keys'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let linkBin = exports.linkBin = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) {
if (process.platform === 'win32') {
const unlockMutex = yield (0, (_mutex || _load_mutex()).default)(src);
try {
yield cmdShim(src, dest);
} finally {
unlockMutex();
}
} else {
yield (_fs || _load_fs()).mkdirp(path.dirname(dest));
yield (_fs || _load_fs()).symlink(src, dest);
yield (_fs || _load_fs()).chmod(dest, '755');
}
});
return function linkBin(_x, _x2) {
return _ref.apply(this, arguments);
};
})();
var _packageHoister;
function _load_packageHoister() {
return _packageHoister = _interopRequireDefault(require('./package-hoister.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('./constants.js'));
}
var _promise2;
function _load_promise2() {
return _promise2 = _interopRequireWildcard(require('./util/promise.js'));
}
var _misc;
function _load_misc() {
return _misc = require('./util/misc.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('./util/fs.js'));
}
var _mutex;
function _load_mutex() {
return _mutex = _interopRequireDefault(require('./util/mutex.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const cmdShim = (_promise2 || _load_promise2()).promisify(require('cmd-shim'));
const semver = require('semver');
const path = require('path');
class PackageLinker {
constructor(config, resolver) {
this.resolver = resolver;
this.reporter = config.reporter;
this.config = config;
}
linkSelfDependencies(pkg, pkgLoc, targetBinLoc) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
targetBinLoc = yield (_fs || _load_fs()).realpath(targetBinLoc);
pkgLoc = yield (_fs || _load_fs()).realpath(pkgLoc);
for (const _ref2 of (0, (_misc || _load_misc()).entries)(pkg.bin)) {
var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 2);
const scriptName = _ref3[0];
const scriptCmd = _ref3[1];
const dest = path.join(targetBinLoc, scriptName);
const src = path.join(pkgLoc, scriptCmd);
if (!(yield (_fs || _load_fs()).exists(src))) {
// TODO maybe throw an error
continue;
}
yield linkBin(src, dest);
}
})();
}
linkBinDependencies(pkg, dir) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const deps = [];
const ref = pkg._reference;
invariant(ref, 'Package reference is missing');
const remote = pkg._remote;
invariant(remote, 'Package remote is missing');
// link up `bin scripts` in `dependencies`
for (const pattern of ref.dependencies) {
const dep = _this.resolver.getStrictResolvedPattern(pattern);
if (dep.bin && (0, (_keys || _load_keys()).default)(dep.bin).length) {
deps.push({ dep: dep, loc: _this.config.generateHardModulePath(dep._reference) });
}
}
// link up the `bin` scripts in bundled dependencies
if (pkg.bundleDependencies) {
for (const depName of pkg.bundleDependencies) {
const loc = path.join(_this.config.generateHardModulePath(ref), _this.config.getFolder(pkg), depName);
const dep = yield _this.config.readManifest(loc, remote.registry);
if (dep.bin && (0, (_keys || _load_keys()).default)(dep.bin).length) {
deps.push({ dep: dep, loc: loc });
}
}
}
// no deps to link
if (!deps.length) {
return;
}
// ensure our .bin file we're writing these to exists
const binLoc = path.join(dir, '.bin');
yield (_fs || _load_fs()).mkdirp(binLoc);
// write the executables
for (const _ref4 of deps) {
const dep = _ref4.dep;
const loc = _ref4.loc;
yield _this.linkSelfDependencies(dep, loc, binLoc);
}
})();
}
getFlatHoistedTree(patterns) {
const hoister = new (_packageHoister || _load_packageHoister()).default(this.config, this.resolver);
hoister.seed(patterns);
return (_promise || _load_promise()).default.resolve(hoister.init());
}
copyModules(patterns, linkDuplicates) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
let flatTree = yield _this2.getFlatHoistedTree(patterns);
// sorted tree makes file creation and copying not to interfere with each other
flatTree = flatTree.sort(function (dep1, dep2) {
return dep1[0].localeCompare(dep2[0]);
});
// list of artifacts in modules to remove from extraneous removal
const artifactFiles = [];
const copyQueue = new (_map || _load_map()).default();
const hardlinkQueue = new (_map || _load_map()).default();
const hardlinksEnabled = linkDuplicates && (yield (_fs || _load_fs()).hardlinksWork(_this2.config.cwd));
const copiedSrcs = new (_map || _load_map()).default();
for (const _ref5 of flatTree) {
var _ref6 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref5, 2);
const dest = _ref6[0];
var _ref6$ = _ref6[1];
const pkg = _ref6$.pkg;
const src = _ref6$.loc;
const ref = pkg._reference;
invariant(ref, 'expected package reference');
ref.setLocation(dest);
// get a list of build artifacts contained in this module so we can prevent them from being marked as
// extraneous
const metadata = yield _this2.config.readPackageMetadata(src);
for (const file of metadata.artifacts) {
artifactFiles.push(path.join(dest, file));
}
const copiedDest = copiedSrcs.get(src);
if (!copiedDest) {
if (hardlinksEnabled) {
copiedSrcs.set(src, dest);
}
copyQueue.set(dest, {
src: src,
dest: dest,
onFresh: function onFresh() {
if (ref) {
ref.setFresh(true);
}
}
});
} else {
hardlinkQueue.set(dest, {
src: copiedDest,
dest: dest,
onFresh: function onFresh() {
if (ref) {
ref.setFresh(true);
}
}
});
}
}
// keep track of all scoped paths to remove empty scopes after copy
const scopedPaths = new (_set || _load_set()).default();
// register root & scoped packages as being possibly extraneous
const possibleExtraneous = new (_set || _load_set()).default();
for (const folder of _this2.config.registryFolders) {
const loc = path.join(_this2.config.cwd, folder);
if (yield (_fs || _load_fs()).exists(loc)) {
const files = yield (_fs || _load_fs()).readdir(loc);
let filepath;
for (const file of files) {
filepath = path.join(loc, file);
if (file[0] === '@') {
// it's a scope, not a package
scopedPaths.add(filepath);
const subfiles = yield (_fs || _load_fs()).readdir(filepath);
for (const subfile of subfiles) {
possibleExtraneous.add(path.join(filepath, subfile));
}
} else {
possibleExtraneous.add(filepath);
}
}
}
}
// linked modules
for (const loc of possibleExtraneous) {
const stat = yield (_fs || _load_fs()).lstat(loc);
if (stat.isSymbolicLink()) {
possibleExtraneous.delete(loc);
copyQueue.delete(loc);
}
}
//
let tick;
yield (_fs || _load_fs()).copyBulk((0, (_from || _load_from()).default)(copyQueue.values()), _this2.reporter, {
possibleExtraneous: possibleExtraneous,
artifactFiles: artifactFiles,
ignoreBasenames: [(_constants || _load_constants()).METADATA_FILENAME, (_constants || _load_constants()).TARBALL_FILENAME],
onStart: function onStart(num) {
tick = _this2.reporter.progress(num);
},
onProgress: function onProgress(src) {
if (tick) {
tick(src);
}
}
});
yield (_fs || _load_fs()).hardlinkBulk((0, (_from || _load_from()).default)(hardlinkQueue.values()), _this2.reporter, {
possibleExtraneous: possibleExtraneous,
artifactFiles: artifactFiles,
onStart: function onStart(num) {
tick = _this2.reporter.progress(num);
},
onProgress: function onProgress(src) {
if (tick) {
tick(src);
}
}
});
// remove all extraneous files that weren't in the tree
for (const loc of possibleExtraneous) {
_this2.reporter.verbose(_this2.reporter.lang('verboseFileRemoveExtraneous', loc));
yield (_fs || _load_fs()).unlink(loc);
}
// remove any empty scoped directories
for (const scopedPath of scopedPaths) {
const files = yield (_fs || _load_fs()).readdir(scopedPath);
if (files.length === 0) {
yield (_fs || _load_fs()).unlink(scopedPath);
}
}
//
if (_this2.config.binLinks) {
const tickBin = _this2.reporter.progress(flatTree.length);
yield (_promise2 || _load_promise2()).queue(flatTree, (() => {
var _ref8 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref7) {
var _ref9 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref7, 2);
let dest = _ref9[0],
pkg = _ref9[1].pkg;
const binLoc = path.join(dest, _this2.config.getFolder(pkg));
yield _this2.linkBinDependencies(pkg, binLoc);
tickBin(dest);
});
return function (_x3) {
return _ref8.apply(this, arguments);
};
})(), 4);
}
})();
}
resolvePeerModules() {
for (const pkg of this.resolver.getManifests()) {
this._resolvePeerModules(pkg);
}
}
_resolvePeerModules(pkg) {
const peerDeps = pkg.peerDependencies;
if (!peerDeps) {
return;
}
const ref = pkg._reference;
invariant(ref, 'Package reference is missing');
for (const name in peerDeps) {
const range = peerDeps[name];
const patterns = this.resolver.patternsByPackage[name] || [];
const foundPattern = patterns.find(pattern => {
const resolvedPattern = this.resolver.getResolvedPattern(pattern);
return resolvedPattern ? this._satisfiesPeerDependency(range, resolvedPattern.version) : false;
});
if (foundPattern) {
ref.addDependencies([foundPattern]);
} else {
const depError = patterns.length > 0 ? 'incorrectPeer' : 'unmetPeer';
const pkgHuman = `${pkg.name}@${pkg.version}`,
depHuman = `${name}@${range}`;
this.reporter.warn(this.reporter.lang(depError, pkgHuman, depHuman));
}
}
}
_satisfiesPeerDependency(range, version) {
return range === '*' || semver.satisfies(version, range, this.config.looseSemver);
}
init(patterns, linkDuplicates) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this3.resolvePeerModules();
yield _this3.copyModules(patterns, linkDuplicates);
yield _this3.saveAll(patterns);
})();
}
save(pattern) {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const resolved = _this4.resolver.getResolvedPattern(pattern);
invariant(resolved, `Couldn't find resolved name/version for ${pattern}`);
const ref = resolved._reference;
invariant(ref, 'Missing reference');
//
const src = _this4.config.generateHardModulePath(ref);
// link bins
if (_this4.config.binLinks && resolved.bin && (0, (_keys || _load_keys()).default)(resolved.bin).length && !ref.ignore) {
const folder = _this4.config.modulesFolder || path.join(_this4.config.cwd, _this4.config.getFolder(resolved));
const binLoc = path.join(folder, '.bin');
yield (_fs || _load_fs()).mkdirp(binLoc);
yield _this4.linkSelfDependencies(resolved, src, binLoc);
}
})();
}
saveAll(deps) {
var _this5 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
deps = _this5.resolver.dedupePatterns(deps);
yield (_promise2 || _load_promise2()).queue(deps, function (dep) {
return _this5.save(dep);
});
})();
}
}
exports.default = PackageLinker;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _misc;
function _load_misc() {
return _misc = require('./util/misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class PackageReference {
constructor(request, info, remote) {
this.resolver = request.resolver;
this.lockfile = request.lockfile;
this.requests = [];
this.config = request.config;
this.registry = remote.registry;
this.version = info.version;
this.name = info.name;
this.uid = info._uid;
this.remote = remote;
this.dependencies = [];
this.permissions = {};
this.patterns = [];
this.optional = null;
this.root = false;
this.ignore = false;
this.fresh = false;
this.location = null;
this.addRequest(request);
}
setFresh(fresh) {
this.fresh = fresh;
}
setLocation(loc) {
return this.location = loc;
}
addRequest(request) {
this.requests.push(request);
if (!request.parentRequest) {
this.root = true;
}
}
prune() {
for (const selfPattern of this.patterns) {
// remove ourselves from the resolver
this.resolver.removePattern(selfPattern);
}
}
addDependencies(deps) {
this.dependencies = this.dependencies.concat(deps);
}
setPermission(key, val) {
this.permissions[key] = val;
}
hasPermission(key) {
if (key in this.permissions) {
return this.permissions[key];
} else {
return false;
}
}
addPattern(pattern, manifest) {
this.resolver.addPattern(pattern, manifest);
this.patterns.push(pattern);
const shrunk = this.lockfile.getLocked(pattern);
if (shrunk && shrunk.permissions) {
for (const _ref of (0, (_misc || _load_misc()).entries)(shrunk.permissions)) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const key = _ref2[0];
const perm = _ref2[1];
this.setPermission(key, perm);
}
}
}
addOptional(optional) {
if (this.optional == null) {
// optional is uninitialised
this.optional = optional;
} else if (!optional) {
// otherwise, ignore all subsequent optional assignments and only accept ones making
// this not optional
this.optional = false;
}
}
}
exports.default = PackageReference;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _assign;
function _load_assign() {
return _assign = _interopRequireDefault(require('babel-runtime/core-js/object/assign'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _validate;
function _load_validate() {
return _validate = require('./util/normalize-manifest/validate.js');
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('./lockfile/wrapper.js'));
}
var _packageReference;
function _load_packageReference() {
return _packageReference = _interopRequireDefault(require('./package-reference.js'));
}
var _index;
function _load_index() {
return _index = _interopRequireWildcard(require('./resolvers/index.js'));
}
var _index2;
function _load_index2() {
return _index2 = require('./resolvers/index.js');
}
var _errors;
function _load_errors() {
return _errors = require('./errors.js');
}
var _misc;
function _load_misc() {
return _misc = require('./util/misc.js');
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('./constants.js'));
}
var _version;
function _load_version() {
return _version = _interopRequireWildcard(require('./util/version.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('./util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
const invariant = require('invariant');
const semver = require('semver');
class PackageRequest {
constructor(req, resolver) {
this.parentRequest = req.parentRequest;
this.lockfile = resolver.lockfile;
this.registry = req.registry;
this.reporter = resolver.reporter;
this.resolver = resolver;
this.optional = req.optional;
this.pattern = req.pattern;
this.config = resolver.config;
resolver.usedRegistries.add(req.registry);
}
static getExoticResolver(pattern) {
// TODO make this type more refined
for (const _ref of (0, (_misc || _load_misc()).entries)((_index || _load_index()).exotics)) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const Resolver = _ref2[1];
if (Resolver.isVersion(pattern)) {
return Resolver;
}
}
return null;
}
getParentNames() {
const chain = [];
let request = this.parentRequest;
while (request) {
const info = this.resolver.getStrictResolvedPattern(request.pattern);
chain.unshift(info.name);
request = request.parentRequest;
}
return chain;
}
getLocked(remoteType) {
// always prioritise root lockfile
const shrunk = this.lockfile.getLocked(this.pattern);
if (shrunk && shrunk.resolved) {
const resolvedParts = (_version || _load_version()).explodeHashedUrl(shrunk.resolved);
return {
name: shrunk.name,
version: shrunk.version,
_uid: shrunk.uid,
_remote: {
resolved: shrunk.resolved,
type: remoteType,
reference: resolvedParts.url,
hash: resolvedParts.hash,
registry: shrunk.registry
},
optionalDependencies: shrunk.optionalDependencies,
dependencies: shrunk.dependencies
};
} else {
return null;
}
}
/**
* If the input pattern matches a registry one then attempt to find it on the registry.
* Otherwise fork off to an exotic resolver if one matches.
*/
findVersionOnRegistry(pattern) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
var _ref3 = yield _this.normalize(pattern);
const range = _ref3.range,
name = _ref3.name;
const exoticResolver = PackageRequest.getExoticResolver(range);
if (exoticResolver) {
let data = yield _this.findExoticVersionInfo(exoticResolver, range);
// clone data as we're manipulating it in place and this could be resolved multiple
// times
data = (0, (_assign || _load_assign()).default)({}, data);
// this is so the returned package response uses the overridden name. ie. if the
// package's actual name is `bar`, but it's been specified in the manifest like:
// "foo": "http://foo.com/bar.tar.gz"
// then we use the foo name
data.name = name;
return data;
}
const Resolver = _this.getRegistryResolver();
const resolver = new Resolver(_this, name, range);
return resolver.resolve();
})();
}
/**
* Get the registry resolver associated with this package request.
*/
getRegistryResolver() {
const Resolver = (_index2 || _load_index2()).registries[this.registry];
if (Resolver) {
return Resolver;
} else {
throw new (_errors || _load_errors()).MessageError(this.reporter.lang('unknownRegistryResolver', this.registry));
}
}
normalizeRange(pattern) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (pattern.includes(':') || pattern.includes('@') || PackageRequest.getExoticResolver(pattern)) {
return (_promise || _load_promise()).default.resolve(pattern);
}
if (yield (_fs || _load_fs()).exists(path.join(_this2.config.cwd, pattern))) {
return (_promise || _load_promise()).default.resolve(`file:${pattern}`);
}
return (_promise || _load_promise()).default.resolve(pattern);
})();
}
normalize(pattern) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
var _PackageRequest$norma = PackageRequest.normalizePattern(pattern);
const name = _PackageRequest$norma.name,
range = _PackageRequest$norma.range,
hasVersion = _PackageRequest$norma.hasVersion;
const newRange = yield _this3.normalizeRange(range);
return { name: name, range: newRange, hasVersion: hasVersion };
})();
}
/**
* Explode and normalize a pattern into it's name and range.
*/
static normalizePattern(pattern) {
let hasVersion = false;
let range = 'latest';
let name = pattern;
// if we're a scope then remove the @ and add it back later
let isScoped = false;
if (name[0] === '@') {
isScoped = true;
name = name.slice(1);
}
// take first part as the name
const parts = name.split('@');
if (parts.length > 1) {
name = parts.shift();
range = parts.join('@');
if (range) {
hasVersion = true;
} else {
range = '*';
}
}
// add back @ scope suffix
if (isScoped) {
name = `@${name}`;
}
return { name: name, range: range, hasVersion: hasVersion };
}
/**
* Construct an exotic resolver instance with the input `ExoticResolver` and `range`.
*/
findExoticVersionInfo(ExoticResolver, range) {
const resolver = new ExoticResolver(this, range);
return resolver.resolve();
}
/**
* If the current pattern matches an exotic resolver then delegate to it or else try
* the registry.
*/
findVersionInfo() {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const exoticResolver = PackageRequest.getExoticResolver(_this4.pattern);
if (exoticResolver) {
return yield _this4.findExoticVersionInfo(exoticResolver, _this4.pattern);
} else {
return yield _this4.findVersionOnRegistry(_this4.pattern);
}
})();
}
reportResolvedRangeMatch(info, resolved) {}
/**
* TODO description
*/
find() {
var _this5 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// find version info for this package pattern
const info = yield _this5.findVersionInfo();
if (!info) {
throw new (_errors || _load_errors()).MessageError(_this5.reporter.lang('unknownPackage', _this5.pattern));
}
(0, (_validate || _load_validate()).cleanDependencies)(info, false, _this5.reporter, function () {
// swallow warnings
});
// check if while we were resolving this dep we've already resolved one that satisfies
// the same range
var _PackageRequest$norma2 = PackageRequest.normalizePattern(_this5.pattern);
const range = _PackageRequest$norma2.range,
name = _PackageRequest$norma2.name;
const resolved = _this5.resolver.getHighestRangeVersionMatch(name, range);
if (resolved) {
_this5.reportResolvedRangeMatch(info, resolved);
const ref = resolved._reference;
invariant(ref, 'Resolved package info has no package reference');
ref.addRequest(_this5);
ref.addPattern(_this5.pattern, resolved);
return;
}
if (info.flat && !_this5.resolver.flat) {
throw new (_errors || _load_errors()).MessageError(_this5.reporter.lang('flatGlobalError'));
}
// validate version info
PackageRequest.validateVersionInfo(info, _this5.reporter);
//
const remote = info._remote;
invariant(remote, 'Missing remote');
// set package reference
const ref = new (_packageReference || _load_packageReference()).default(_this5, info, remote);
ref.addPattern(_this5.pattern, info);
ref.addOptional(_this5.optional);
info._reference = ref;
info._remote = remote;
// start installation of dependencies
const promises = [];
const deps = [];
// normal deps
for (const depName in info.dependencies) {
const depPattern = depName + '@' + info.dependencies[depName];
deps.push(depPattern);
promises.push(_this5.resolver.find({
pattern: depPattern,
registry: remote.registry,
optional: false,
parentRequest: _this5
}));
}
// optional deps
for (const depName in info.optionalDependencies) {
const depPattern = depName + '@' + info.optionalDependencies[depName];
deps.push(depPattern);
promises.push(_this5.resolver.find({
pattern: depPattern,
registry: remote.registry,
optional: true,
parentRequest: _this5
}));
}
yield (_promise || _load_promise()).default.all(promises);
ref.addDependencies(deps);
// Now that we have all dependencies, it's safe to propagate optional
for (const otherRequest of ref.requests.slice(1)) {
ref.addOptional(otherRequest.optional);
}
})();
}
/**
* TODO description
*/
static validateVersionInfo(info, reporter) {
// human readable name to use in errors
const human = `${info.name}@${info.version}`;
info.version = PackageRequest.getPackageVersion(info);
for (const key of (_constants || _load_constants()).REQUIRED_PACKAGE_KEYS) {
if (!info[key]) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('missingRequiredPackageKey', human, key));
}
}
}
/**
* Returns the package version if present, else defaults to the uid
*/
static getPackageVersion(info) {
// TODO possibly reconsider this behaviour
return info.version === undefined ? info._uid : info.version;
}
/**
* Gets all of the outdated packages and sorts them appropriately
*/
static getOutdatedPackages(lockfile, install, config, reporter) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
var _ref4 = yield install.fetchRequestFromCwd();
const depReqPatterns = _ref4.requests;
const deps = yield (_promise || _load_promise()).default.all(depReqPatterns.map((() => {
var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref5) {
let pattern = _ref5.pattern,
hint = _ref5.hint;
const locked = lockfile.getLocked(pattern);
if (!locked) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('lockfileOutdated'));
}
const name = locked.name,
current = locked.version;
let latest = '';
let wanted = '';
let url = '';
const normalized = PackageRequest.normalizePattern(pattern);
if (PackageRequest.getExoticResolver(pattern) || PackageRequest.getExoticResolver(normalized.range)) {
latest = wanted = 'exotic';
url = normalized.range;
} else {
const registry = config.registries[locked.registry];
var _ref7 = yield registry.checkOutdated(config, name, normalized.range);
latest = _ref7.latest;
wanted = _ref7.wanted;
url = _ref7.url;
}
return { name: name, current: current, wanted: wanted, latest: latest, url: url, hint: hint };
});
return function (_x) {
return _ref6.apply(this, arguments);
};
})()));
// Make sure to always output `exotic` versions to be compatible with npm
const isDepOld = function isDepOld(_ref8) {
let current = _ref8.current,
latest = _ref8.latest,
wanted = _ref8.wanted;
return latest === 'exotic' || latest !== 'exotic' && (semver.lt(current, wanted) || semver.lt(current, latest));
};
const orderByName = function orderByName(depA, depB) {
return depA.name.localeCompare(depB.name);
};
return deps.filter(isDepOld).sort(orderByName);
})();
}
}
exports.default = PackageRequest;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _set;
function _load_set() {
return _set = _interopRequireDefault(require('babel-runtime/core-js/set'));
}
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('./package-request.js'));
}
var _requestManager;
function _load_requestManager() {
return _requestManager = _interopRequireDefault(require('./util/request-manager.js'));
}
var _blockingQueue;
function _load_blockingQueue() {
return _blockingQueue = _interopRequireDefault(require('./util/blocking-queue.js'));
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('./lockfile/wrapper.js'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('./util/map.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const semver = require('semver');
class PackageResolver {
constructor(config, lockfile) {
this.patternsByPackage = (0, (_map || _load_map()).default)();
this.fetchingPatterns = (0, (_map || _load_map()).default)();
this.fetchingQueue = new (_blockingQueue || _load_blockingQueue()).default('resolver fetching');
this.newPatterns = [];
this.patterns = (0, (_map || _load_map()).default)();
this.usedRegistries = new (_set || _load_set()).default();
this.flat = false;
this.reporter = config.reporter;
this.lockfile = lockfile;
this.config = config;
}
// whether the dependency graph will be flattened
// list of registries that have been used in this resolution
// activity monitor
// patterns we've already resolved or are in the process of resolving
// new patterns that didn't exist in the lockfile
// TODO
// these are patterns that the package resolver was seeded with. these are required in
// order to resolve top level peerDependencies
// manages and throttles json api http requests
// list of patterns associated with a package
// lockfile instance which we can use to retrieve version info
// a map of dependency patterns to packages
// reporter instance, abstracts out display logic
// environment specific config methods and options
/**
* TODO description
*/
isNewPattern(pattern) {
return this.newPatterns.indexOf(pattern) >= 0;
}
/**
* TODO description
*/
updateManifest(ref, newPkg) {
// inherit fields
const oldPkg = this.patterns[ref.patterns[0]];
newPkg._reference = ref;
newPkg._remote = ref.remote;
newPkg.name = oldPkg.name;
// update patterns
for (const pattern of ref.patterns) {
this.patterns[pattern] = newPkg;
}
return (_promise || _load_promise()).default.resolve();
}
/**
* Given a list of patterns, dedupe them to a list of unique patterns.
*/
dedupePatterns(patterns) {
const deduped = [];
const seen = new (_set || _load_set()).default();
for (const pattern of patterns) {
const info = this.getResolvedPattern(pattern);
if (seen.has(info)) {
continue;
}
seen.add(info);
deduped.push(pattern);
}
return deduped;
}
/**
* Get a list of all manifests by topological order.
*/
getTopologicalManifests(seedPatterns) {
const pkgs = new (_set || _load_set()).default();
const skip = new (_set || _load_set()).default();
const add = seedPatterns => {
for (const pattern of seedPatterns) {
const pkg = this.getStrictResolvedPattern(pattern);
if (skip.has(pkg)) {
continue;
}
const ref = pkg._reference;
invariant(ref, 'expected reference');
skip.add(pkg);
add(ref.dependencies);
pkgs.add(pkg);
}
};
add(seedPatterns);
return pkgs;
}
/**
* Get a list of all manifests by level sort order.
*/
getLevelOrderManifests(seedPatterns) {
const pkgs = new (_set || _load_set()).default();
const skip = new (_set || _load_set()).default();
const add = seedPatterns => {
const refs = [];
for (const pattern of seedPatterns) {
const pkg = this.getStrictResolvedPattern(pattern);
if (skip.has(pkg)) {
continue;
}
const ref = pkg._reference;
invariant(ref, 'expected reference');
refs.push(ref);
skip.add(pkg);
pkgs.add(pkg);
}
for (const ref of refs) {
add(ref.dependencies);
}
};
add(seedPatterns);
return pkgs;
}
/**
* Get a list of all package names in the depenency graph.
*/
getAllDependencyNamesByLevelOrder(seedPatterns) {
const names = new (_set || _load_set()).default();
for (const _ref of this.getLevelOrderManifests(seedPatterns)) {
const name = _ref.name;
names.add(name);
}
return names;
}
/**
* Retrieve all the package info stored for this package name.
*/
getAllInfoForPackageName(name) {
const infos = [];
const seen = new (_set || _load_set()).default();
for (const pattern of this.patternsByPackage[name]) {
const info = this.patterns[pattern];
if (seen.has(info)) {
continue;
}
seen.add(info);
infos.push(info);
}
return infos;
}
/**
* Get a flat list of all package references.
*/
getPackageReferences() {
const refs = [];
for (const manifest of this.getManifests()) {
const ref = manifest._reference;
if (ref) {
refs.push(ref);
}
}
return refs;
}
/**
* Get a flat list of all package info.
*/
getManifests() {
const infos = [];
const seen = new (_set || _load_set()).default();
for (const pattern in this.patterns) {
const info = this.patterns[pattern];
if (seen.has(info)) {
continue;
}
infos.push(info);
seen.add(info);
}
return infos;
}
/**
* replace pattern in resolver, e.g. `name` is replaced with `name@^1.0.1`
*/
replacePattern(pattern, newPattern) {
const pkg = this.getResolvedPattern(pattern);
invariant(pkg, `missing package ${pattern}`);
const ref = pkg._reference;
invariant(ref, 'expected package reference');
ref.patterns = [newPattern];
this.newPatterns.splice(this.newPatterns.indexOf(pattern), 1, newPattern);
this.addPattern(newPattern, pkg);
this.removePattern(pattern);
}
/**
* Make all versions of this package resolve to it.
*/
collapseAllVersionsOfPackage(name, version) {
const patterns = this.dedupePatterns(this.patternsByPackage[name]);
const human = `${name}@${version}`;
// get manifest that matches the version we're collapsing too
let collapseToReference;
let collapseToManifest;
let collapseToPattern;
for (const pattern of patterns) {
const _manifest = this.patterns[pattern];
if (_manifest.version === version) {
collapseToReference = _manifest._reference;
collapseToManifest = _manifest;
collapseToPattern = pattern;
break;
}
}
invariant(collapseToReference && collapseToManifest && collapseToPattern, `Couldn't find package manifest for ${human}`);
for (const pattern of patterns) {
// don't touch the pattern we're collapsing to
if (pattern === collapseToPattern) {
continue;
}
// remove this pattern
const ref = this.getStrictResolvedPattern(pattern)._reference;
invariant(ref, 'expected package reference');
const refPatterns = ref.patterns.slice();
ref.prune();
// add pattern to the manifest we're collapsing to
for (const pattern of refPatterns) {
collapseToReference.addPattern(pattern, collapseToManifest);
}
}
return collapseToPattern;
}
/**
* TODO description
*/
addPattern(pattern, info) {
this.patterns[pattern] = info;
const byName = this.patternsByPackage[info.name] = this.patternsByPackage[info.name] || [];
byName.push(pattern);
}
/**
* TODO description
*/
removePattern(pattern) {
const pkg = this.patterns[pattern];
if (!pkg) {
return;
}
const byName = this.patternsByPackage[pkg.name];
if (!byName) {
return;
}
byName.splice(byName.indexOf(pattern), 1);
delete this.patterns[pattern];
}
/**
* TODO description
*/
getResolvedPattern(pattern) {
return this.patterns[pattern];
}
/**
* TODO description
*/
getStrictResolvedPattern(pattern) {
const manifest = this.getResolvedPattern(pattern);
invariant(manifest, 'expected manifest');
return manifest;
}
/**
* TODO description
*/
getExactVersionMatch(name, version) {
const patterns = this.patternsByPackage[name];
if (!patterns) {
return null;
}
for (const pattern of patterns) {
const info = this.getStrictResolvedPattern(pattern);
if (info.version === version) {
return info;
}
}
return null;
}
/**
* Get the manifest of the highest known version that satisfies a package range
*/
getHighestRangeVersionMatch(name, range) {
const patterns = this.patternsByPackage[name];
if (!patterns) {
return null;
}
const versionNumbers = [];
const resolvedPatterns = patterns.map(pattern => {
const info = this.getStrictResolvedPattern(pattern);
versionNumbers.push(info.version);
return info;
});
const maxValidRange = semver.maxSatisfying(versionNumbers, range);
if (!maxValidRange) {
return null;
}
const indexOfmaxValidRange = versionNumbers.indexOf(maxValidRange);
const maxValidRangeManifest = resolvedPatterns[indexOfmaxValidRange];
return maxValidRangeManifest;
}
/**
* TODO description
*/
find(req) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const fetchKey = `${req.registry}:${req.pattern}`;
if (_this.fetchingPatterns[fetchKey]) {
return;
} else {
_this.fetchingPatterns[fetchKey] = true;
}
if (_this.activity) {
_this.activity.tick(req.pattern);
}
if (!_this.lockfile.getLocked(req.pattern, true)) {
_this.newPatterns.push(req.pattern);
}
const request = new (_packageRequest || _load_packageRequest()).default(req, _this);
yield request.find();
})();
}
/**
* TODO description
*/
init(deps, isFlat) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this2.flat = isFlat;
//
const activity = _this2.activity = _this2.reporter.activity();
//
_this2.seedPatterns = deps.map(function (dep) {
return dep.pattern;
});
//
yield (_promise || _load_promise()).default.all(deps.map(function (req) {
return _this2.find(req);
}));
activity.end();
_this2.activity = null;
})();
}
}
exports.default = PackageResolver;
|
| 1 2 | 'use strict'; |
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| parse.js | 10.75% | (20 / 186) | 0% | (0 / 110) | 0% | (0 / 15) | 10.81% | (20 / 185) | |
| stringify.js | 29.31% | (17 / 58) | 0% | (0 / 55) | 0% | (0 / 10) | 29.82% | (17 / 57) | |
| wrapper.js | 36.7% | (40 / 109) | 8.54% | (7 / 82) | 21.74% | (5 / 23) | 39.39% | (39 / 99) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Parser = undefined;
exports.tokenise = tokenise;
exports.default = function (str) {
let fileLoc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'lockfile';
str = stripBOM(str);
const parser = new Parser(str, fileLoc);
parser.next();
return parser.parse();
};
var _constants;
function _load_constants() {
return _constants = require('../constants.js');
}
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('../util/map.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
/* eslint quotes: 0 */
const stripBOM = require('strip-bom');
const VERSION_REGEX = /^yarn lockfile v(\d+)$/;
const TOKEN_TYPES = {
boolean: 'BOOLEAN',
string: 'STRING',
identifier: 'IDENTIFIER',
eof: 'EOF',
colon: 'COLON',
newline: 'NEWLINE',
comment: 'COMMENT',
indent: 'INDENT',
invalid: 'INVALID',
number: 'NUMBER',
comma: 'COMMA'
};
const VALID_PROP_VALUE_TOKENS = [TOKEN_TYPES.boolean, TOKEN_TYPES.string, TOKEN_TYPES.number];
function isValidPropValueToken(token) {
return VALID_PROP_VALUE_TOKENS.indexOf(token.type) >= 0;
}
function* tokenise(input) {
let lastNewline = false;
let line = 1;
let col = 0;
function buildToken(type, value) {
return { line: line, col: col, type: type, value: value };
}
while (input.length) {
let chop = 0;
if (input[0] === '\n') {
chop++;
line++;
col = 0;
yield buildToken(TOKEN_TYPES.newline);
} else if (input[0] === '#') {
chop++;
let val = '';
while (input[chop] !== '\n') {
val += input[chop];
chop++;
}
yield buildToken(TOKEN_TYPES.comment, val);
} else if (input[0] === ' ') {
if (lastNewline) {
let indent = '';
for (let i = 0; input[i] === ' '; i++) {
indent += input[i];
}
if (indent.length % 2) {
throw new TypeError('Invalid number of spaces');
} else {
chop = indent.length;
yield buildToken(TOKEN_TYPES.indent, indent.length / 2);
}
} else {
chop++;
}
} else if (input[0] === '"') {
let val = '';
for (let i = 0;; i++) {
const currentChar = input[i];
val += currentChar;
if (i > 0 && currentChar === '"') {
const isEscaped = input[i - 1] === "\\" && input[i - 2] !== "\\";
if (!isEscaped) {
break;
}
}
}
chop = val.length;
try {
yield buildToken(TOKEN_TYPES.string, JSON.parse(val));
} catch (err) {
if (err instanceof SyntaxError) {
yield buildToken(TOKEN_TYPES.invalid);
} else {
throw err;
}
}
} else if (/^[0-9]/.test(input)) {
let val = '';
for (let i = 0; /^[0-9]$/.test(input[i]); i++) {
val += input[i];
}
chop = val.length;
yield buildToken(TOKEN_TYPES.number, +val);
} else if (/^true/.test(input)) {
yield buildToken(TOKEN_TYPES.boolean, true);
chop = 4;
} else if (/^false/.test(input)) {
yield buildToken(TOKEN_TYPES.boolean, false);
chop = 5;
} else if (input[0] === ':') {
yield buildToken(TOKEN_TYPES.colon);
chop++;
} else if (input[0] === ',') {
yield buildToken(TOKEN_TYPES.comma);
chop++;
} else if (/^[a-zA-Z]/g.test(input)) {
let name = "";
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (char === ':' || char === ' ' || char === '\n' || char === ',') {
break;
} else {
name += char;
}
}
chop = name.length;
yield buildToken(TOKEN_TYPES.string, name);
} else {
yield buildToken(TOKEN_TYPES.invalid);
}
if (!chop) {
// will trigger infinite recursion
yield buildToken(TOKEN_TYPES.invalid);
}
col += chop;
lastNewline = input[0] === '\n';
input = input.slice(chop);
}
yield buildToken(TOKEN_TYPES.eof);
}
class Parser {
constructor(input) {
let fileLoc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'lockfile';
this.comments = [];
this.tokens = tokenise(input);
this.fileLoc = fileLoc;
}
onComment(token) {
const value = token.value;
invariant(typeof value === 'string', 'expected token value to be a string');
const comment = value.trim();
const versionMatch = comment.match(VERSION_REGEX);
if (versionMatch) {
const version = +versionMatch[1];
if (version > (_constants || _load_constants()).LOCKFILE_VERSION) {
throw new (_errors || _load_errors()).MessageError(`Can't install from a lockfile of version ${version} as you're on an old yarn version that only supports ` + `versions up to ${(_constants || _load_constants()).LOCKFILE_VERSION}. Run \`$ yarn self-update\` to upgrade to the latest version.`);
}
}
this.comments.push(comment);
}
next() {
const item = this.tokens.next();
invariant(item, 'expected a token');
const done = item.done,
value = item.value;
if (done || !value) {
throw new Error('No more tokens');
} else if (value.type === TOKEN_TYPES.comment) {
this.onComment(value);
return this.next();
} else {
return this.token = value;
}
}
unexpected() {
let msg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'Unexpected token';
throw new SyntaxError(`${msg} ${this.token.line}:${this.token.col} in ${this.fileLoc}`);
}
expect(tokType) {
if (this.token.type === tokType) {
this.next();
} else {
this.unexpected();
}
}
eat(tokType) {
if (this.token.type === tokType) {
this.next();
return true;
} else {
return false;
}
}
parse() {
let indent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
const obj = (0, (_map || _load_map()).default)();
while (true) {
const propToken = this.token;
if (propToken.type === TOKEN_TYPES.newline) {
const nextToken = this.next();
if (!indent) {
// if we have 0 indentation then the next token doesn't matter
continue;
}
if (nextToken.type !== TOKEN_TYPES.indent) {
// if we have no indentation after a newline then we've gone down a level
break;
}
if (nextToken.value === indent) {
// all is good, the indent is on our level
this.next();
} else {
// the indentation is less than our level
break;
}
} else if (propToken.type === TOKEN_TYPES.indent) {
if (propToken.value === indent) {
this.next();
} else {
break;
}
} else if (propToken.type === TOKEN_TYPES.eof) {
break;
} else if (propToken.type === TOKEN_TYPES.string) {
// property key
const key = propToken.value;
invariant(key, 'Expected a key');
const keys = [key];
this.next();
// support multiple keys
while (this.token.type === TOKEN_TYPES.comma) {
this.next(); // skip comma
const keyToken = this.token;
if (keyToken.type !== TOKEN_TYPES.string) {
this.unexpected('Expected string');
}
const key = keyToken.value;
invariant(key, 'Expected a key');
keys.push(key);
this.next();
}
const valToken = this.token;
if (valToken.type === TOKEN_TYPES.colon) {
// object
this.next();
// parse object
const val = this.parse(indent + 1);
for (const key of keys) {
obj[key] = val;
}
if (indent && this.token.type !== TOKEN_TYPES.indent) {
break;
}
} else if (isValidPropValueToken(valToken)) {
// plain value
for (const key of keys) {
obj[key] = valToken.value;
}
this.next();
} else {
this.unexpected('Invalid value type');
}
} else {
this.unexpected('Unknown token');
}
}
return obj;
}
}
exports.Parser = Parser;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys;
function _load_keys() {
return _keys = _interopRequireDefault(require('babel-runtime/core-js/object/keys'));
}
var _stringify2;
function _load_stringify() {
return _stringify2 = _interopRequireDefault(require('babel-runtime/core-js/json/stringify'));
}
exports.default = stringify;
var _misc;
function _load_misc() {
return _misc = require('../util/misc.js');
}
var _constants;
function _load_constants() {
return _constants = require('../constants.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function shouldWrapKey(str) {
return str.indexOf('true') === 0 || str.indexOf('false') === 0 || /[:\s\n\\",\[\]]/g.test(str) || /^[0-9]/g.test(str) || !/^[a-zA-Z]/g.test(str);
}
function maybeWrap(str) {
if (typeof str === 'boolean' || typeof str === 'number' || shouldWrapKey(str)) {
return (0, (_stringify2 || _load_stringify()).default)(str);
} else {
return str;
}
}
const priorities = {
name: 1,
version: 2,
uid: 3,
resolved: 4,
registry: 5,
dependencies: 6
};
function priorityThenAlphaSort(a, b) {
if (priorities[a] || priorities[b]) {
return (priorities[a] || 100) > (priorities[b] || 100) ? 1 : -1;
} else {
return (0, (_misc || _load_misc()).sortAlpha)(a, b);
}
}
function _stringify(obj, options) {
if (typeof obj !== 'object') {
throw new TypeError();
}
const indent = options.indent;
const lines = [];
// Sorting order needs to be consistent between runs, we run native sort by name because there are no
// problems with it being unstable because there are no to keys the same
// However priorities can be duplicated and native sort can shuffle things from run to run
const keys = (0, (_keys || _load_keys()).default)(obj).sort(priorityThenAlphaSort);
let addedKeys = [];
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const val = obj[key];
if (val == null || addedKeys.indexOf(key) >= 0) {
continue;
}
//
const valKeys = [key];
// get all keys that have the same value equality, we only want this for objects
if (typeof val === 'object') {
for (let j = i + 1; j < keys.length; j++) {
const key = keys[j];
if (val === obj[key]) {
valKeys.push(key);
}
}
}
//
const keyLine = valKeys.sort((_misc || _load_misc()).sortAlpha).map(maybeWrap).join(', ');
if (typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number') {
lines.push(`${keyLine} ${maybeWrap(val)}`);
} else if (typeof val === 'object') {
lines.push(`${keyLine}:\n${_stringify(val, { indent: indent + ' ' })}` + (options.topLevel ? '\n' : ''));
} else {
throw new TypeError();
}
addedKeys = addedKeys.concat(valKeys);
}
return indent + lines.join(`\n${indent}`);
}
function stringify(obj, noHeader) {
const val = _stringify(obj, {
indent: '',
topLevel: true
});
if (noHeader) {
return val;
}
return ['# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.', `# yarn lockfile v${(_constants || _load_constants()).LOCKFILE_VERSION}`, '\n', val].join('\n');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | 1 1 1 1 1 1 1 1 1 1 1 1 4 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 6 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.stringify = exports.parse = undefined;
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('babel-runtime/core-js/map'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _keys;
function _load_keys() {
return _keys = _interopRequireDefault(require('babel-runtime/core-js/object/keys'));
}
var _parse;
function _load_parse() {
return _parse = require('./parse');
}
Object.defineProperty(exports, 'parse', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_parse || _load_parse()).default;
}
});
var _stringify;
function _load_stringify() {
return _stringify = require('./stringify');
}
Object.defineProperty(exports, 'stringify', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_stringify || _load_stringify()).default;
}
});
exports.implodeEntry = implodeEntry;
exports.explodeEntry = explodeEntry;
var _misc;
function _load_misc() {
return _misc = require('../util/misc.js');
}
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('../package-request.js'));
}
var _parse2;
function _load_parse2() {
return _parse2 = _interopRequireDefault(require('./parse.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const path = require('path');
function getName(pattern) {
return (_packageRequest || _load_packageRequest()).default.normalizePattern(pattern).name;
}
function blankObjectUndefined(obj) {
return obj && (0, (_keys || _load_keys()).default)(obj).length ? obj : undefined;
}
function implodeEntry(pattern, obj) {
const inferredName = getName(pattern);
return {
name: inferredName === obj.name ? undefined : obj.name,
version: obj.version,
uid: obj.uid === obj.version ? undefined : obj.uid,
resolved: obj.resolved,
registry: obj.registry === 'npm' ? undefined : obj.registry,
dependencies: blankObjectUndefined(obj.dependencies),
optionalDependencies: blankObjectUndefined(obj.optionalDependencies),
permissions: blankObjectUndefined(obj.permissions)
};
}
function explodeEntry(pattern, obj) {
obj.optionalDependencies = obj.optionalDependencies || {};
obj.dependencies = obj.dependencies || {};
obj.uid = obj.uid || obj.version;
obj.permissions = obj.permissions || {};
obj.registry = obj.registry || 'npm';
obj.name = obj.name || getName(pattern);
return obj;
}
class Lockfile {
constructor(cache, source) {
this.source = source || '';
this.cache = cache;
}
// source string if the `cache` was parsed
static fromDirectory(dir, reporter) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// read the manifest in this directory
const lockfileLoc = path.join(dir, (_constants || _load_constants()).LOCKFILE_FILENAME);
let lockfile;
let rawLockfile = '';
if (yield (_fs || _load_fs()).exists(lockfileLoc)) {
rawLockfile = yield (_fs || _load_fs()).readFile(lockfileLoc);
lockfile = (0, (_parse2 || _load_parse2()).default)(rawLockfile, lockfileLoc);
} else {
if (reporter) {
reporter.info(reporter.lang('noLockfileFound'));
}
}
return new Lockfile(lockfile, rawLockfile);
})();
}
getLocked(pattern) {
const cache = this.cache;
if (!cache) {
return undefined;
}
const shrunk = pattern in cache && cache[pattern];
if (typeof shrunk === 'string') {
return this.getLocked(shrunk);
} else if (shrunk) {
explodeEntry(pattern, shrunk);
return shrunk;
}
return undefined;
}
getLockfile(patterns) {
const lockfile = {};
const seen = new (_map || _load_map()).default();
// order by name so that lockfile manifest is assigned to the first dependency with this manifest
// the others that have the same remote.resolved will just refer to the first
// ordering allows for consistency in lockfile when it is serialized
const sortedPatternsKeys = (0, (_keys || _load_keys()).default)(patterns).sort((_misc || _load_misc()).sortAlpha);
for (const pattern of sortedPatternsKeys) {
const pkg = patterns[pattern];
const remote = pkg._remote,
ref = pkg._reference;
invariant(ref, 'Package is missing a reference');
invariant(remote, 'Package is missing a remote');
const seenPattern = remote.resolved && seen.get(remote.resolved);
if (seenPattern) {
// no point in duplicating it
lockfile[pattern] = seenPattern;
// if we're relying on our name being inferred and two of the patterns have
// different inferred names then we need to set it
if (!seenPattern.name && getName(pattern) !== pkg.name) {
seenPattern.name = pkg.name;
}
continue;
}
const obj = implodeEntry(pattern, {
name: pkg.name,
version: pkg.version,
uid: pkg._uid,
resolved: remote.resolved,
registry: remote.registry,
dependencies: pkg.dependencies,
peerDependencies: pkg.peerDependencies,
optionalDependencies: pkg.optionalDependencies,
permissions: ref.permissions
});
lockfile[pattern] = obj;
if (remote.resolved) {
seen.set(remote.resolved, obj);
}
}
return lockfile;
}
}
exports.default = Lockfile;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| base-registry.js | 24.19% | (15 / 62) | 0% | (0 / 32) | 0% | (0 / 19) | 24.59% | (15 / 61) | |
| is-request-to-registry.js | 31.82% | (7 / 22) | 0% | (0 / 24) | 0% | (0 / 4) | 33.33% | (7 / 21) | |
| npm-registry.js | 22.79% | (31 / 136) | 4.9% | (5 / 102) | 8% | (2 / 25) | 24% | (30 / 125) | |
| yarn-registry.js | 37.04% | (30 / 81) | 14.58% | (7 / 48) | 18.75% | (3 / 16) | 40.85% | (29 / 71) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _keys;
function _load_keys() {
return _keys = _interopRequireDefault(require('babel-runtime/core-js/object/keys'));
}
var _misc;
function _load_misc() {
return _misc = require('../util/misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const objectPath = require('object-path');
const path = require('path');
class BaseRegistry {
constructor(cwd, registries, requestManager) {
this.requestManager = requestManager;
this.registries = registries;
this.config = {};
this.folder = '';
this.token = '';
this.loc = '';
this.cwd = cwd;
}
// the filename to use for package metadata
//
//
//
//
//
// absolute folder name to insert modules
// relative folder name to put these modules
setToken(token) {
this.token = token;
}
getOption(key) {
return this.config[key];
}
getAvailableRegistries() {
const config = this.config;
return (0, (_keys || _load_keys()).default)(config).reduce((registries, option) => {
if (option === 'registry' || option.split(':')[1] === 'registry') {
registries.push(config[option]);
}
return registries;
}, []);
}
loadConfig() {
return (_promise || _load_promise()).default.resolve();
}
checkOutdated(config, name, range) {
return (_promise || _load_promise()).default.reject(new Error('unimplemented'));
}
saveHomeConfig(config) {
return (_promise || _load_promise()).default.reject(new Error('unimplemented'));
}
request(pathname) {
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.requestManager.request((0, (_extends2 || _load_extends()).default)({
url: pathname
}, opts));
}
init() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this.mergeEnv('yarn_');
yield _this.loadConfig();
_this.loc = path.join(_this.cwd, _this.folder);
})();
}
static normalizeConfig(config) {
for (const key in config) {
config[key] = BaseRegistry.normalizeConfigOption(config[key]);
}
return config;
}
static normalizeConfigOption(val) {
if (val === 'true') {
return true;
} else if (val === 'false') {
return false;
} else {
return val;
}
}
mergeEnv(prefix) {
// try environment variables
for (let key in process.env) {
key = key.toLowerCase();
// only accept keys prefixed with the prefix
if (key.indexOf(prefix) < 0) {
continue;
}
const val = BaseRegistry.normalizeConfigOption(process.env[key]);
// remove config prefix
key = (0, (_misc || _load_misc()).removePrefix)(key, prefix);
// replace dunders with dots
key = key.replace(/__/g, '.');
// replace underscores with dashes
key = key.replace(/_/g, '-');
// set it via a path
objectPath.set(this.config, key, val);
}
}
}
exports.default = BaseRegistry;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isRequestToRegistry;
var _url;
function _load_url() {
return _url = _interopRequireDefault(require('url'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isRequestToRegistry(requestUrl, registry) {
const requestParsed = (_url || _load_url()).default.parse(requestUrl);
const registryParsed = (_url || _load_url()).default.parse(registry);
const requestPort = getPortOrDefaultPort(requestParsed.port, requestParsed.protocol);
const registryPort = getPortOrDefaultPort(registryParsed.port, registryParsed.protocol);
const requestPath = requestParsed.path || '';
const registryPath = registryParsed.path || '';
return requestParsed.protocol === registryParsed.protocol && requestParsed.hostname === registryParsed.hostname && requestPort === registryPort && requestPath.startsWith(registryPath);
}
function getPortOrDefaultPort(port, protocol) {
const defaultPort = !port;
if (defaultPort && protocol === 'https:') {
return '443';
}
if (defaultPort && protocol === 'http:') {
return '80';
}
return port;
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _assign;
function _load_assign() {
return _assign = _interopRequireDefault(require('babel-runtime/core-js/object/assign'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../util/fs.js'));
}
var _npmResolver;
function _load_npmResolver() {
return _npmResolver = _interopRequireDefault(require('../resolvers/registries/npm-resolver.js'));
}
var _envReplace;
function _load_envReplace() {
return _envReplace = _interopRequireDefault(require('../util/env-replace.js'));
}
var _baseRegistry;
function _load_baseRegistry() {
return _baseRegistry = _interopRequireDefault(require('./base-registry.js'));
}
var _misc;
function _load_misc() {
return _misc = require('../util/misc');
}
var _isRequestToRegistry;
function _load_isRequestToRegistry() {
return _isRequestToRegistry = _interopRequireDefault(require('./is-request-to-registry.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const userHome = require('../util/user-home-dir').default;
const path = require('path');
const url = require('url');
const ini = require('ini');
const DEFAULT_REGISTRY = 'https://registry.npmjs.org/';
function getGlobalPrefix() {
if (process.env.PREFIX) {
return process.env.PREFIX;
} else if (process.platform === 'win32') {
// c:\node\node.exe --> prefix=c:\node\
return path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
let prefix = path.dirname(path.dirname(process.execPath));
// destdir only is respected on Unix
if (process.env.DESTDIR) {
prefix = path.join(process.env.DESTDIR, prefix);
}
return prefix;
}
}
class NpmRegistry extends (_baseRegistry || _load_baseRegistry()).default {
constructor(cwd, registries, requestManager) {
super(cwd, registries, requestManager);
this.folder = 'node_modules';
}
static escapeName(name) {
// scoped packages contain slashes and the npm registry expects them to be escaped
return name.replace('/', '%2f');
}
request(pathname) {
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const registry = (0, (_misc || _load_misc()).addSuffix)(this.getRegistry(pathname), '/');
const requestUrl = url.resolve(registry, pathname);
const alwaysAuth = this.getScopedOption(registry.replace(/^https?:/, ''), 'always-auth') || this.getOption('always-auth') || (0, (_misc || _load_misc()).removePrefix)(requestUrl, registry)[0] === '@';
const headers = {};
if (this.token || alwaysAuth && (0, (_isRequestToRegistry || _load_isRequestToRegistry()).default)(requestUrl, registry)) {
const authorization = this.getAuth(pathname);
if (authorization) {
headers.authorization = authorization;
}
}
return this.requestManager.request({
url: requestUrl,
method: opts.method,
body: opts.body,
auth: opts.auth,
headers: headers,
json: !opts.buffer,
buffer: opts.buffer,
process: opts.process,
gzip: true
});
}
checkOutdated(config, name, range) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const req = yield _this.request(NpmRegistry.escapeName(name));
if (!req) {
throw new Error('couldnt find ' + name);
}
const repository = req.repository,
homepage = req.homepage;
const url = homepage || repository && repository.url || '';
return {
latest: req['dist-tags'].latest,
wanted: (yield (_npmResolver || _load_npmResolver()).default.findVersionInRegistryResponse(config, range, req)).version,
url: url
};
})();
}
getPossibleConfigLocations(filename) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const possibles = [[false, path.join(_this2.cwd, filename)], [true, _this2.config.userconfig || path.join(userHome, filename)], [false, path.join(getGlobalPrefix(), filename)]];
const foldersFromRootToCwd = _this2.cwd.split(path.sep);
while (foldersFromRootToCwd.length > 1) {
possibles.push([false, path.join(foldersFromRootToCwd.join(path.sep), filename)]);
foldersFromRootToCwd.pop();
}
const actuals = [];
for (const _ref of possibles) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const isHome = _ref2[0];
const loc = _ref2[1];
if (yield (_fs || _load_fs()).exists(loc)) {
actuals.push([isHome, loc, yield (_fs || _load_fs()).readFile(loc)]);
}
}
return actuals;
})();
}
loadConfig() {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// docs: https://docs.npmjs.com/misc/config
_this3.mergeEnv('npm_config_');
for (const _ref3 of yield _this3.getPossibleConfigLocations('.npmrc')) {
var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 3);
const loc = _ref4[1];
const file = _ref4[2];
const config = (_baseRegistry || _load_baseRegistry()).default.normalizeConfig(ini.parse(file));
for (const key in config) {
config[key] = (0, (_envReplace || _load_envReplace()).default)(config[key]);
}
// normalize offline mirror path relative to the current npmrc
const offlineLoc = config['yarn-offline-mirror'];
// don't normalize if we already have a mirror path
if (!_this3.config['yarn-offline-mirror'] && offlineLoc) {
const mirrorLoc = config['yarn-offline-mirror'] = path.resolve(path.dirname(loc), offlineLoc);
yield (_fs || _load_fs()).mkdirp(mirrorLoc);
}
_this3.config = (0, (_assign || _load_assign()).default)({}, config, _this3.config);
}
})();
}
getScope(packageName) {
return !packageName || packageName[0] !== '@' ? '' : packageName.split(/\/|%2f/)[0];
}
getRegistry(packageName) {
// Try extracting registry from the url, then scoped registry, and default registry
if (packageName.match(/^https?:/)) {
const availableRegistries = this.getAvailableRegistries();
const registry = availableRegistries.find(registry => packageName.startsWith(registry));
if (registry) {
return registry;
}
}
for (const scope of [this.getScope(packageName), '']) {
const registry = this.getScopedOption(scope, 'registry') || this.registries.yarn.getScopedOption(scope, 'registry');
if (registry) {
return String(registry);
}
}
return DEFAULT_REGISTRY;
}
getAuth(packageName) {
if (this.token) {
return this.token;
}
for (let registry of [this.getRegistry(packageName), '', DEFAULT_REGISTRY]) {
registry = registry.replace(/^https?:/, '');
// Check for bearer token.
let auth = this.getScopedOption(registry.replace(/\/?$/, '/'), '_authToken');
if (auth) {
return `Bearer ${String(auth)}`;
}
// Check for basic auth token.
auth = this.getScopedOption(registry, '_auth');
if (auth) {
return `Basic ${String(auth)}`;
}
// Check for basic username/password auth.
const username = this.getScopedOption(registry, 'username');
const password = this.getScopedOption(registry, '_password');
if (username && password) {
const pw = new Buffer(String(password), 'base64').toString();
return 'Basic ' + new Buffer(String(username) + ':' + pw).toString('base64');
}
}
return '';
}
getScopedOption(scope, option) {
return this.getOption(scope + (scope ? ':' : '') + option);
}
}
exports.default = NpmRegistry;
NpmRegistry.filename = 'package.json';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DEFAULTS = undefined;
var _assign;
function _load_assign() {
return _assign = _interopRequireDefault(require('babel-runtime/core-js/object/assign'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _constants;
function _load_constants() {
return _constants = require('../constants.js');
}
var _npmRegistry;
function _load_npmRegistry() {
return _npmRegistry = _interopRequireDefault(require('./npm-registry.js'));
}
var _stringify;
function _load_stringify() {
return _stringify = _interopRequireDefault(require('../lockfile/stringify.js'));
}
var _parse;
function _load_parse() {
return _parse = _interopRequireDefault(require('../lockfile/parse.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const userHome = require('../util/user-home-dir').default;
const path = require('path');
const pkg = require('../../package.json');
const DEFAULTS = exports.DEFAULTS = {
'version-tag-prefix': 'v',
'version-git-tag': true,
'version-git-sign': false,
'version-git-message': 'v%s',
'init-version': '1.0.0',
'init-license': 'MIT',
'save-prefix': '^',
'ignore-scripts': false,
'ignore-optional': false,
registry: (_constants || _load_constants()).YARN_REGISTRY,
'strict-ssl': true,
'user-agent': [`yarn/${pkg.version}`, 'npm/?', `node/${process.version}`, process.platform, process.arch].join(' ')
};
const npmMap = {
'version-git-sign': 'sign-git-tag',
'version-tag-prefix': 'tag-version-prefix',
'version-git-tag': 'git-tag-version',
'version-git-message': 'message'
};
class YarnRegistry extends (_npmRegistry || _load_npmRegistry()).default {
constructor(cwd, registries, requestManager) {
super(cwd, registries, requestManager);
this.homeConfigLoc = path.join(userHome, '.yarnrc');
this.homeConfig = {};
}
getOption(key) {
let val = this.config[key];
// if this isn't set in a yarn config, then use npm
if (typeof val === 'undefined') {
val = this.registries.npm.getOption(npmMap[key]);
}
if (typeof val === 'undefined') {
val = this.registries.npm.getOption(key);
}
// if this isn't set in a yarn config or npm config, then use the default (or undefined)
if (typeof val === 'undefined') {
val = DEFAULTS[key];
}
return val;
}
loadConfig() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
for (const _ref of yield _this.getPossibleConfigLocations('.yarnrc')) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 3);
const isHome = _ref2[0];
const loc = _ref2[1];
const file = _ref2[2];
const config = (0, (_parse || _load_parse()).default)(file, loc);
if (isHome) {
_this.homeConfig = config;
}
// normalize offline mirror path relative to the current yarnrc
const offlineLoc = config['yarn-offline-mirror'];
// don't normalize if we already have a mirror path
if (!_this.config['yarn-offline-mirror'] && offlineLoc) {
const mirrorLoc = config['yarn-offline-mirror'] = path.resolve(path.dirname(loc), offlineLoc);
yield (_fs || _load_fs()).mkdirp(mirrorLoc);
}
_this.config = (0, (_assign || _load_assign()).default)({}, config, _this.config);
}
// default yarn config
_this.config = (0, (_assign || _load_assign()).default)({}, DEFAULTS, _this.config);
})();
}
saveHomeConfig(config) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
YarnRegistry.normalizeConfig(config);
for (const key in config) {
const val = config[key];
// if the current config key was taken from home config then update
// the global config
if (_this2.homeConfig[key] === _this2.config[key]) {
_this2.config[key] = val;
}
// update just the home config
_this2.homeConfig[key] = config[key];
}
yield (_fs || _load_fs()).writeFilePreservingEol(_this2.homeConfigLoc, `${(0, (_stringify || _load_stringify()).default)(_this2.homeConfig)}\n`);
})();
}
}
exports.default = YarnRegistry;
YarnRegistry.filename = 'yarn.json';
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| base-reporter.js | 19.05% | (20 / 105) | 0% | (0 / 70) | 0% | (0 / 50) | 21.05% | (20 / 95) | |
| buffer-reporter.js | 63.64% | (7 / 11) | 83.33% | (5 / 6) | 40% | (2 / 5) | 60% | (6 / 10) | |
| event-reporter.js | 81.25% | (13 / 16) | 87.5% | (7 / 8) | 60% | (3 / 5) | 80% | (12 / 15) | |
| format.js | 50% | (3 / 6) | 100% | (0 / 0) | 0% | (0 / 1) | 50% | (3 / 6) | |
| json-reporter.js | 18.64% | (11 / 59) | 35.71% | (5 / 14) | 7.69% | (2 / 26) | 17.24% | (10 / 58) | |
| noop-reporter.js | 40% | (18 / 45) | 20.83% | (5 / 24) | 4.55% | (2 / 44) | 48.57% | (17 / 35) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _stringify;
function _load_stringify() {
return _stringify = _interopRequireDefault(require('babel-runtime/core-js/json/stringify'));
}
exports.stringifyLangArgs = stringifyLangArgs;
var _format;
function _load_format() {
return _format = require('./format.js');
}
var _index;
function _load_index() {
return _index = _interopRequireWildcard(require('./lang/index.js'));
}
var _isCi;
function _load_isCi() {
return _isCi = _interopRequireDefault(require('is-ci'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint no-unused-vars: 0 */
const util = require('util');
const EventEmitter = require('events').EventEmitter;
function stringifyLangArgs(args) {
return args.map(function (val) {
if (val != null && val.inspect) {
return val.inspect();
} else {
try {
const str = (0, (_stringify || _load_stringify()).default)(val) || val + '';
// should match all "u001b" that follow an odd number of backslashes and convert them to ESC
// we do this because the JSON.stringify process has escaped these characters
return str.replace(/((?:^|[^\\])(?:\\{2})*)\\u001[bB]/g, '$1\u001b');
} catch (e) {
return util.inspect(val);
}
}
});
}
class BaseReporter {
constructor() {
let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const lang = 'en';
this.language = lang;
this.stdout = opts.stdout || process.stdout;
this.stderr = opts.stderr || process.stderr;
this.stdin = opts.stdin || this._getStandardInput();
this.emoji = !!opts.emoji;
this.noProgress = !!opts.noProgress || (_isCi || _load_isCi()).default;
this.isVerbose = !!opts.verbose;
// $FlowFixMe: this is valid!
this.isTTY = this.stdout.isTTY;
this.peakMemory = 0;
this.startTime = Date.now();
this.format = (_format || _load_format()).defaultFormatter;
}
lang(key) {
const msg = (_index || _load_index())[this.language][key] || (_index || _load_index()).en[key];
if (!msg) {
throw new ReferenceError(`Unknown language key ${key}`);
}
// stringify args
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
const stringifiedArgs = stringifyLangArgs(args);
// replace $0 placeholders with args
return msg.replace(/\$(\d+)/g, (str, i) => {
return stringifiedArgs[i];
});
}
verbose(msg) {
if (this.isVerbose) {
this._verbose(msg);
}
}
verboseInspect(val) {
if (this.isVerbose) {
this._verboseInspect(val);
}
}
_verbose(msg) {}
_verboseInspect(val) {}
_getStandardInput() {
let standardInput;
try {
standardInput = process.stdin;
} catch (e) {
delete process.stdin;
// $FlowFixMe: this is valid!
process.stdin = new EventEmitter();
standardInput = process.stdin;
}
return standardInput;
}
initPeakMemoryCounter() {
this.checkPeakMemory();
this.peakMemoryInterval = setInterval(() => {
this.checkPeakMemory();
}, 1000);
}
checkPeakMemory() {
var _process$memoryUsage = process.memoryUsage();
const heapTotal = _process$memoryUsage.heapTotal;
if (heapTotal > this.peakMemory) {
this.peakMemory = heapTotal;
}
}
close() {
if (this.peakMemoryInterval) {
clearInterval(this.peakMemoryInterval);
this.peakMemoryInterval = null;
}
}
getTotalTime() {
return Date.now() - this.startTime;
}
// TODO
list(key, items, hints) {}
// Outputs basic tree structure to console
tree(key, obj) {}
// called whenever we begin a step in the CLI.
step(current, total, message, emoji) {}
// a error message has been triggered. this however does not always meant an abrupt
// program end.
error(message) {}
// an info message has been triggered. this provides things like stats and diagnostics.
info(message) {}
// a warning message has been triggered.
warn(message) {}
// a success message has been triggered.
success(message) {}
// a simple log message
log(message) {}
// a shell command has been executed
command(command) {}
// inspect and pretty-print any value
inspect(value) {}
// the screen shown at the very start of the CLI
header(command, pkg) {}
// the screen shown at the very end of the CLI
footer(showPeakMemory) {}
//
table(head, body) {}
// render an activity spinner and return a function that will trigger an update
activity() {
return {
tick: function tick(name) {},
end: function end() {}
};
}
//
activitySet(total, workers) {
return {
spinners: Array(workers).fill({
clear: function clear() {},
setPrefix: function setPrefix() {},
tick: function tick() {},
end: function end() {}
}),
end: function end() {}
};
}
//
question(question) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return (_promise || _load_promise()).default.reject(new Error('Not implemented'));
}
//
questionAffirm(question) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const condition = true; // trick eslint
while (condition) {
let answer = yield _this.question(question);
answer = answer.toLowerCase();
if (answer === 'y' || answer === 'yes') {
return true;
}
if (answer === 'n' || answer === 'no') {
return false;
}
_this.error('Invalid answer for question');
}
return false;
})();
}
// prompt the user to select an option from an array
select(header, question, options) {
return (_promise || _load_promise()).default.reject(new Error('Not implemented'));
}
// render a progress bar and return a function which when called will trigger an update
progress(total) {
return function () {};
}
// utility function to disable progress bar
disableProgress() {
this.noProgress = true;
}
}
exports.default = BaseReporter;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jsonReporter;
function _load_jsonReporter() {
return _jsonReporter = _interopRequireDefault(require('./json-reporter.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class BufferReporter extends (_jsonReporter || _load_jsonReporter()).default {
constructor(opts) {
super(opts);
this._buffer = [];
}
_dump(type, data, error) {
this._buffer.push({
type: type,
data: data,
error: !!error
});
}
getBuffer() {
return this._buffer;
}
}
exports.default = BufferReporter;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 1 1 1 1 1 1 1 2 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _assign;
function _load_assign() {
return _assign = _interopRequireDefault(require('babel-runtime/core-js/object/assign'));
}
var _jsonReporter;
function _load_jsonReporter() {
return _jsonReporter = _interopRequireDefault(require('./json-reporter.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('events');
const EventEmitter = _require.EventEmitter;
class EventReporter extends (_jsonReporter || _load_jsonReporter()).default {
constructor(opts) {
super(opts);
// $FlowFixMe: looks like a flow bug
EventEmitter.call(this);
}
_dump(type, data) {
this.emit(type, data);
}
}
exports.default = EventReporter; // $FlowFixMe: need to "inherit" from it
(0, (_assign || _load_assign()).default)(EventReporter.prototype, EventEmitter.prototype);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function formatFunction() {
for (var _len = arguments.length, strs = Array(_len), _key = 0; _key < _len; _key++) {
strs[_key] = arguments[_key];
}
return strs.join(' ');
}
const defaultFormatter = exports.defaultFormatter = {
bold: formatFunction,
dim: formatFunction,
italic: formatFunction,
underline: formatFunction,
inverse: formatFunction,
strikethrough: formatFunction,
black: formatFunction,
red: formatFunction,
green: formatFunction,
yellow: formatFunction,
blue: formatFunction,
magenta: formatFunction,
cyan: formatFunction,
white: formatFunction,
gray: formatFunction,
grey: formatFunction,
stripColor: formatFunction
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _stringify;
function _load_stringify() {
return _stringify = _interopRequireDefault(require('babel-runtime/core-js/json/stringify'));
}
var _baseReporter;
function _load_baseReporter() {
return _baseReporter = _interopRequireDefault(require('./base-reporter.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class JSONReporter extends (_baseReporter || _load_baseReporter()).default {
constructor(opts) {
super(opts);
this._activityId = 0;
this._progressId = 0;
}
_dump(type, data, error) {
let stdout = this.stdout;
if (error) {
stdout = this.stderr;
}
stdout.write(`${(0, (_stringify || _load_stringify()).default)({ type: type, data: data })}\n`);
}
_verbose(msg) {
this._dump('verbose', msg);
}
list(type, items, hints) {
this._dump('list', { type: type, items: items, hints: hints });
}
tree(type, trees) {
this._dump('tree', { type: type, trees: trees });
}
step(current, total, message) {
this._dump('step', { message: message, current: current, total: total });
}
inspect(value) {
this._dump('inspect', value);
}
footer() {
this._dump('finished', this.getTotalTime());
}
log(msg) {
this._dump('log', msg);
}
command(msg) {
this._dump('command', msg);
}
table(head, body) {
this._dump('table', { head: head, body: body });
}
success(msg) {
this._dump('success', msg);
}
error(msg) {
this._dump('error', msg, true);
}
warn(msg) {
this._dump('warning', msg, true);
}
info(msg) {
this._dump('info', msg);
}
activitySet(total, workers) {
const id = this._activityId++;
this._dump('activitySetStart', { id: id, total: total, workers: workers });
const spinners = [];
for (let i = 0; i < workers; i++) {
let current = 0;
let header = '';
spinners.push({
clear: function clear() {},
setPrefix: function setPrefix(_current, _header) {
current = _current;
header = _header;
},
tick: msg => {
this._dump('activitySetTick', { id: id, header: header, current: current, worker: i, message: msg });
},
end: function end() {}
});
}
return {
spinners: spinners,
end: () => {
this._dump('activitySetEnd', { id: id });
}
};
}
activity() {
return this._activity({});
}
_activity(data) {
const id = this._activityId++;
this._dump('activityStart', (0, (_extends2 || _load_extends()).default)({ id: id }, data));
return {
tick: name => {
this._dump('activityTick', { id: id, name: name });
},
end: () => {
this._dump('activityEnd', { id: id });
}
};
}
progress(total) {
const id = this._progressId++;
let current = 0;
this._dump('progressStart', { id: id, total: total });
return () => {
current++;
this._dump('progressTick', { id: id, current: current });
if (current === total) {
this._dump('progressFinish', { id: id });
}
};
}
}
exports.default = JSONReporter;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _format;
function _load_format() {
return _format = require('./format.js');
}
var _index;
function _load_index() {
return _index = _interopRequireWildcard(require('./lang/index.js'));
}
var _isCi;
function _load_isCi() {
return _isCi = _interopRequireDefault(require('is-ci'));
}
var _baseReporter;
function _load_baseReporter() {
return _baseReporter = _interopRequireDefault(require('./base-reporter.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class NoopReporter extends (_baseReporter || _load_baseReporter()).default {
lang(key) {
return 'do nothing';
}
verbose(msg) {}
verboseInspect(val) {}
initPeakMemoryCounter() {}
checkPeakMemory() {}
close() {}
getTotalTime() {
return 0;
}
list(key, items, hints) {}
tree(key, obj) {}
step(current, total, message, emoji) {}
error(message) {}
info(message) {}
warn(message) {}
success(message) {}
log(message) {}
command(command) {}
inspect(value) {}
header(command, pkg) {}
footer(showPeakMemory) {}
table(head, body) {}
activity() {
return {
tick: function tick(name) {},
end: function end() {}
};
}
activitySet(total, workers) {
return {
spinners: Array(workers).fill({
clear: function clear() {},
setPrefix: function setPrefix() {},
tick: function tick() {},
end: function end() {}
}),
end: function end() {}
};
}
question(question) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return (_promise || _load_promise()).default.reject(new Error('Not implemented'));
}
questionAffirm(question) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield _this.question(question);
return false;
})();
}
select(header, question, options) {
return (_promise || _load_promise()).default.reject(new Error('Not implemented'));
}
progress(total) {
return function () {};
}
disableProgress() {
this.noProgress = true;
}
}
exports.default = NoopReporter;
/* eslint no-unused-vars: 0 */
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| console-reporter.js | 14.29% | (27 / 189) | 4.95% | (5 / 101) | 4.55% | (2 / 44) | 14.13% | (26 / 184) | |
| progress-bar.js | 15.15% | (5 / 33) | 0% | (0 / 14) | 0% | (0 / 4) | 15.63% | (5 / 32) | |
| spinner-progress.js | 15.15% | (5 / 33) | 0% | (0 / 18) | 0% | (0 / 7) | 15.63% | (5 / 32) | |
| util.js | 32.56% | (14 / 43) | 0% | (0 / 12) | 0% | (0 / 4) | 32.56% | (14 / 43) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _toConsumableArray2;
function _load_toConsumableArray() {
return _toConsumableArray2 = _interopRequireDefault(require('babel-runtime/helpers/toConsumableArray'));
}
var _baseReporter;
function _load_baseReporter() {
return _baseReporter = _interopRequireDefault(require('../base-reporter.js'));
}
var _progressBar;
function _load_progressBar() {
return _progressBar = _interopRequireDefault(require('./progress-bar.js'));
}
var _spinnerProgress;
function _load_spinnerProgress() {
return _spinnerProgress = _interopRequireDefault(require('./spinner-progress.js'));
}
var _util;
function _load_util() {
return _util = require('./util.js');
}
var _misc;
function _load_misc() {
return _misc = require('../../util/misc.js');
}
var _treeHelper;
function _load_treeHelper() {
return _treeHelper = require('./helpers/tree-helper.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('util');
const inspect = _require.inspect;
const readline = require('readline');
const chalk = require('chalk');
const read = require('read');
class ConsoleReporter extends (_baseReporter || _load_baseReporter()).default {
constructor(opts) {
super(opts);
this._lastCategorySize = 0;
this.format = chalk;
}
_prependEmoji(msg, emoji) {
if (this.emoji && emoji && this.isTTY) {
msg = `${emoji} ${msg}`;
}
return msg;
}
_logCategory(category, color, msg) {
this._lastCategorySize = category.length;
this._log(`${this.format[color](category)} ${msg}`);
}
_verbose(msg) {
this._logCategory('verbose', 'grey', `${process.uptime()} ${msg}`);
}
_verboseInspect(obj) {
this.inspect(obj);
}
table(head, body) {
//
head = head.map(field => this.format.underline(field));
//
const rows = [head].concat(body);
// get column widths
const cols = [];
for (let i = 0; i < head.length; i++) {
const widths = rows.map(row => this.format.stripColor(row[i]).length);
cols[i] = Math.max.apply(Math, (0, (_toConsumableArray2 || _load_toConsumableArray()).default)(widths));
}
//
const builtRows = rows.map(row => {
for (let i = 0; i < row.length; i++) {
const field = row[i];
const padding = cols[i] - this.format.stripColor(field).length;
row[i] = field + ' '.repeat(padding);
}
return row.join(' ');
});
this.log(builtRows.join('\n'));
}
step(current, total, msg, emoji) {
msg = this._prependEmoji(msg, emoji);
if (msg.endsWith('?')) {
msg = `${(0, (_misc || _load_misc()).removeSuffix)(msg, '?')}...?`;
} else {
msg += '...';
}
this.log(`${this.format.dim(`[${current}/${total}]`)} ${msg}`);
}
inspect(value) {
if (typeof value !== 'number' && typeof value !== 'string') {
value = inspect(value, {
breakLength: 0,
colors: true,
depth: null,
maxArrayLength: null
});
}
this.log('' + value);
}
list(key, items, hints) {
const gutterWidth = (this._lastCategorySize || 2) - 1;
if (hints) {
for (const item of items) {
this._log(`${' '.repeat(gutterWidth)}- ${item}`);
this._log(` ${' '.repeat(gutterWidth)} ${hints[item]}`);
}
} else {
for (const item of items) {
this._log(`${' '.repeat(gutterWidth)}- ${item}`);
}
}
}
header(command, pkg) {
this.log(this.format.bold(`${pkg.name} ${command} v${pkg.version}`));
}
footer(showPeakMemory) {
const totalTime = (this.getTotalTime() / 1000).toFixed(2);
let msg = `Done in ${totalTime}s.`;
if (showPeakMemory) {
const peakMemory = (this.peakMemory / 1024 / 1024).toFixed(2);
msg += ` Peak memory usage ${peakMemory}MB.`;
}
this.log(this._prependEmoji(msg, '✨'));
}
log(msg) {
this._lastCategorySize = 0;
this._log(msg);
}
_log(msg) {
(0, (_util || _load_util()).clearLine)(this.stdout);
this.stdout.write(`${msg}\n`);
}
success(msg) {
this._logCategory('success', 'green', msg);
}
error(msg) {
(0, (_util || _load_util()).clearLine)(this.stderr);
this.stderr.write(`${this.format.red('error')} ${msg}\n`);
}
info(msg) {
this._logCategory('info', 'blue', msg);
}
command(command) {
this.log(this.format.dim(`$ ${command}`));
}
warn(msg) {
(0, (_util || _load_util()).clearLine)(this.stderr);
this.stderr.write(`${this.format.yellow('warning')} ${msg}\n`);
}
question(question) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!process.stdout.isTTY) {
return (_promise || _load_promise()).default.reject(new Error("Can't answer a question unless a user TTY"));
}
return new (_promise || _load_promise()).default((resolve, reject) => {
read({
prompt: `${this.format.dim('question')} ${question}: `,
silent: !!options.password,
output: this.stdout,
input: this.stdin
}, (err, answer) => {
if (err) {
if (err.message === 'canceled') {
process.exit(1);
} else {
reject(err);
}
} else {
if (!answer && options.required) {
this.error(this.lang('answerRequired'));
resolve(this.question(question, options));
} else {
resolve(answer);
}
}
});
});
}
// handles basic tree output to console
tree(key, trees) {
//
const output = (_ref, level, end) => {
let name = _ref.name,
children = _ref.children,
hint = _ref.hint,
color = _ref.color;
const formatter = this.format;
const out = (0, (_treeHelper || _load_treeHelper()).getFormattedOutput)({ end: end, level: level, hint: hint, color: color, name: name, formatter: formatter });
this.stdout.write(out);
if (children && children.length) {
(0, (_treeHelper || _load_treeHelper()).recurseTree)((0, (_treeHelper || _load_treeHelper()).sortTrees)(children), level, output);
}
};
(0, (_treeHelper || _load_treeHelper()).recurseTree)((0, (_treeHelper || _load_treeHelper()).sortTrees)(trees), -1, output);
}
activitySet(total, workers) {
if (!this.isTTY || this.noProgress) {
return super.activitySet(total, workers);
}
const spinners = [];
for (let i = 1; i < workers; i++) {
this.log('');
}
for (let i = 0; i < workers; i++) {
const spinner = new (_spinnerProgress || _load_spinnerProgress()).default(this.stderr, i);
spinner.start();
let prefix = null;
let current = 0;
const updatePrefix = () => {
spinner.setPrefix(`${this.format.dim(`[${current === 0 ? '-' : current}/${total}]`)} `);
};
const clear = () => {
prefix = null;
current = 0;
updatePrefix();
spinner.setText('waiting...');
};
clear();
spinners.unshift({
clear: clear,
setPrefix: function setPrefix(_current, _prefix) {
current = _current;
prefix = _prefix;
spinner.setText(prefix);
updatePrefix();
},
tick: function tick(msg) {
if (prefix) {
msg = `${prefix}: ${msg}`;
}
spinner.setText(msg);
},
end: function end() {
spinner.stop();
}
});
}
return {
spinners: spinners,
end: () => {
for (const spinner of spinners) {
spinner.end();
}
readline.moveCursor(this.stdout, 0, -workers + 1);
}
};
}
activity() {
if (!this.isTTY) {
return {
tick: function tick() {},
end: function end() {}
};
}
const spinner = new (_spinnerProgress || _load_spinnerProgress()).default(this.stderr);
spinner.start();
return {
tick: function tick(name) {
spinner.setText(name);
},
end: function end() {
spinner.stop();
}
};
}
select(header, question, options) {
if (!this.isTTY) {
return (_promise || _load_promise()).default.reject(new Error("Can't answer a question unless a user TTY"));
}
const rl = readline.createInterface({
input: this.stdin,
output: this.stdout,
terminal: true
});
const questions = options.map(opt => opt.name);
const answers = options.map(opt => opt.value);
function toIndex(input) {
const index = answers.indexOf(input);
if (index >= 0) {
return index;
} else {
return +input;
}
}
return new (_promise || _load_promise()).default(resolve => {
this.info(header);
for (let i = 0; i < questions.length; i++) {
this.log(` ${this.format.dim(`${i + 1})`)} ${questions[i]}`);
}
const ask = () => {
rl.question(`${question}: `, input => {
let index = toIndex(input);
if (isNaN(index)) {
this.log('Not a number');
ask();
return;
}
if (index <= 0 || index > options.length) {
this.log('Outside answer range');
ask();
return;
}
// get index
index--;
rl.close();
resolve(answers[index]);
});
};
ask();
});
}
progress(count) {
if (this.noProgress || count <= 0) {
return function () {
// noop
};
}
if (!this.isTTY) {
return function () {
// TODO what should the behaviour here be? we could buffer progress messages maybe
};
}
const bar = new (_progressBar || _load_progressBar()).default(count, this.stderr);
bar.render();
return function () {
bar.tick();
};
}
}
exports.default = ConsoleReporter;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _util;
function _load_util() {
return _util = require('./util.js');
}
class ProgressBar {
constructor(total) {
let stdout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.stderr;
this.stdout = stdout;
this.total = total;
this.chars = ProgressBar.bars[0];
this.delay = 60;
this.curr = 0;
(0, (_util || _load_util()).clearLine)(stdout);
}
tick() {
this.curr++;
// schedule render
if (!this.id) {
this.id = setTimeout(() => this.render(), this.delay);
}
// progress complete
if (this.curr >= this.total) {
clearTimeout(this.id);
(0, (_util || _load_util()).clearLine)(this.stdout);
}
}
render() {
// clear throttle
clearTimeout(this.id);
this.id = null;
let ratio = this.curr / this.total;
ratio = Math.min(Math.max(ratio, 0), 1);
// progress without bar
let bar = ` ${this.curr}/${this.total}`;
// calculate size of actual bar
// $FlowFixMe: investigate process.stderr.columns flow error
const availableSpace = Math.max(0, this.stdout.columns - bar.length - 1);
const width = Math.min(this.total, availableSpace);
const completeLength = Math.round(width * ratio);
const complete = this.chars[0].repeat(completeLength);
const incomplete = this.chars[1].repeat(width - completeLength);
bar = `${complete}${incomplete}${bar}`;
(0, (_util || _load_util()).toStartOfLine)(this.stdout);
this.stdout.write(bar);
}
}
exports.default = ProgressBar;
ProgressBar.bars = [['█', '░']];
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _util;
function _load_util() {
return _util = require('./util.js');
}
class Spinner {
constructor() {
let stdout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : process.stderr;
let lineNumber = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
this.current = 0;
this.prefix = '';
this.lineNumber = lineNumber;
this.stdout = stdout;
this.delay = 60;
this.chars = Spinner.spinners[28].split('');
this.text = '';
this.id = null;
}
setPrefix(prefix) {
this.prefix = prefix;
}
setText(text) {
this.text = text;
}
start() {
this.current = 0;
this.render();
}
render() {
if (this.id) {
clearTimeout(this.id);
}
// build line ensuring we don't wrap to the next line
let msg = `${this.prefix}${this.chars[this.current]} ${this.text}`;
const columns = typeof this.stdout.columns === 'number' ? this.stdout.columns : 100;
msg = msg.slice(0, columns);
(0, (_util || _load_util()).writeOnNthLine)(this.stdout, this.lineNumber, msg);
this.current = ++this.current % this.chars.length;
this.id = setTimeout(() => this.render(), this.delay);
}
stop() {
if (this.id) {
clearTimeout(this.id);
this.id = null;
}
(0, (_util || _load_util()).clearNthLine)(this.stdout, this.lineNumber);
}
}
exports.default = Spinner;
Spinner.spinners = ['|/-\\', '⠂-–—–-', '◐◓◑◒', '◴◷◶◵', '◰◳◲◱', '▖▘▝▗', '■□▪▫', '▌▀▐▄', '▉▊▋▌▍▎▏▎▍▌▋▊▉', '▁▃▄▅▆▇█▇▆▅▄▃', '←↖↑↗→↘↓↙', '┤┘┴└├┌┬┐', '◢◣◤◥', '.oO°Oo.', '.oO@*', '🌍🌎🌏', '◡◡ ⊙⊙ ◠◠', '☱☲☴', '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏', '⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓', '⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆', '⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋', '⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁', '⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈', '⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈', '⢄⢂⢁⡁⡈⡐⡠', '⢹⢺⢼⣸⣇⡧⡗⡏', '⣾⣽⣻⢿⡿⣟⣯⣷', '⠁⠂⠄⡀⢀⠠⠐⠈'];
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.clearLine = clearLine;
exports.toStartOfLine = toStartOfLine;
exports.writeOnNthLine = writeOnNthLine;
exports.clearNthLine = clearNthLine;
const readline = require('readline');
var _require = require('chalk');
const supportsColor = _require.supportsColor;
const CLEAR_WHOLE_LINE = 0;
const CLEAR_RIGHT_OF_CURSOR = 1;
function clearLine(stdout) {
if (!supportsColor) {
return;
}
readline.clearLine(stdout, CLEAR_WHOLE_LINE);
readline.cursorTo(stdout, 0);
}
function toStartOfLine(stdout) {
if (!supportsColor) {
return;
}
readline.cursorTo(stdout, 0);
}
function writeOnNthLine(stdout, n, msg) {
if (!supportsColor) {
return;
}
if (n == 0) {
readline.cursorTo(stdout, 0);
stdout.write(msg);
readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);
return;
}
readline.cursorTo(stdout, 0);
readline.moveCursor(stdout, 0, -n);
stdout.write(msg);
readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);
readline.cursorTo(stdout, 0);
readline.moveCursor(stdout, 0, n);
}
function clearNthLine(stdout, n) {
if (!supportsColor) {
return;
}
if (n == 0) {
clearLine(stdout);
return;
}
readline.cursorTo(stdout, 0);
readline.moveCursor(stdout, 0, -n);
readline.clearLine(stdout, CLEAR_WHOLE_LINE);
readline.moveCursor(stdout, 0, n);
}
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| en.js | 100% | (3 / 3) | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (3 / 3) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/* eslint max-len: 0 */
const messages = {
upToDate: 'Already up-to-date.',
folderInSync: 'Folder in sync.',
nothingToInstall: 'Nothing to install.',
resolvingPackages: 'Resolving packages',
fetchingPackages: 'Fetching packages',
linkingDependencies: 'Linking dependencies',
rebuildingPackages: 'Rebuilding all packages',
buildingFreshPackages: 'Building fresh packages',
cleaningModules: 'Cleaning modules',
bumpingVersion: 'Bumping version',
savingHar: 'Saving HAR file: $0',
answer: 'Answer?',
usage: 'Usage',
installCommandRenamed: '`install` has been replaced with `add` to add new dependencies. Run $0 instead.',
waitingInstance: 'Waiting for the other yarn instance to finish',
offlineRetrying: 'There appears to be trouble with your network connection. Retrying...',
clearedCache: 'Cleared cache.',
packWroteTarball: 'Wrote tarball to $0.',
manifestPotentialTypo: 'Potential typo $0, did you mean $1?',
manifestBuiltinModule: '$0 is also the name of a node core module',
manifestNameDot: "Name can't start with a dot",
manifestNameIllegalChars: 'Name contains illegal characters',
manifestNameBlacklisted: 'Name is blacklisted',
manifestLicenseInvalid: 'License should be a valid SPDX license expression',
manifestLicenseNone: 'No license field',
manifestStringExpected: '$0 is not a string',
manifestDependencyCollision: '$0 has dependency $1 with range $2 that collides with a dependency in $3 of the same name with version $4',
manifestDirectoryNotFound: 'Unable to read $0 directory of module $1',
verboseFileCopy: 'Copying $0 to $1.',
verboseFileLink: 'Creating hardlink at $0 to $1.',
verboseFileSymlink: 'Creating symlink at $0 to $1.',
verboseFileSkip: 'Skipping copying of file $0 as the file at $1 is the same size ($2) and mtime ($3).',
verboseFileSkipSymlink: 'Skipping copying of $0 as the file at $1 is the same symlink ($2).',
verboseFileSkipHardlink: 'Skipping copying of $0 as the file at $1 is the same hardlink ($2).',
verboseFileRemoveExtraneous: 'Removing extraneous file $0.',
verboseFilePhantomExtraneous: "File $0 would be marked as extraneous but has been removed as it's listed as a phantom file.",
verboseFileFolder: 'Creating directory $0.',
verboseRequestStart: 'Performing $0 request to $1.',
verboseRequestFinish: 'Request $0 finished with status code $1.',
configSet: 'Set $0 to $1.',
configDelete: 'Deleted $0.',
configNpm: 'npm config',
configYarn: 'yarn config',
couldntFindPackagejson: "Couldn't find a package.json file in $0",
couldntFindMatch: "Couldn't find match for $0 in $1 for $2.",
couldntFindPackageInCache: "Couldn't find any versions for $0 that matches $1 in our cache. Possible versions: $2",
couldntFindVersionThatMatchesRange: "Couldn't find any versions for $0 that matches $1",
chooseVersionFromList: 'Please choose a version from this list:',
moduleNotInManifest: "This module isn't specified in a manifest.",
unknownFolderOrTarball: "Passed folder/tarball doesn't exist,",
unknownPackage: "Couldn't find package $0.",
unknownPackageName: "Couldn't find package name.",
unknownUser: "Couldn't find user $0.",
unknownRegistryResolver: 'Unknown registry resolver $0',
userNotAnOwner: "User $0 isn't an owner of this package.",
invalidVersionArgument: 'Use the $0 flag to create a new version.',
invalidVersion: 'Invalid version supplied.',
requiredVersionInRange: 'Required version in range.',
packageNotFoundRegistry: "Couldn't find package $0 on the $1 registry.",
doesntExist: "$0 doesn't exist.",
missingRequiredPackageKey: `Package $0 doesn't have a $1.`,
invalidAccess: 'Invalid argument for access, expected public or restricted.',
invalidCommand: 'Invalid subcommand. Try $0',
invalidGistFragment: 'Invalid gist fragment $0.',
invalidHostedGitFragment: 'Invalid hosted git fragment $0.',
invalidFragment: 'Invalid fragment $0.',
invalidPackageName: 'Invalid package name.',
couldntFindManifestIn: "Couldn't find manifest in $0.",
shrinkwrapWarning: 'npm-shrinkwrap.json found. This will not be updated or respected. See https://yarnpkg.com/en/docs/migrating-from-npm for more information.',
lockfileOutdated: 'Outdated lockfile. Please run `yarn install` and try again.',
ignoredScripts: 'Ignored scripts due to flag.',
missingAddDependencies: 'Missing list of packages to add to your project.',
yesWarning: 'The yes flag has been set. This will automatically answer yes to all questions which may have security implications.',
networkWarning: "You don't appear to have an internet connection. Try the --offline flag to use the cache for registry queries.",
flatGlobalError: 'The package $0@$1 requires a flat dependency graph. Add `"flat": true` to your package.json and try again.',
noName: `Package doesn't have a name.`,
noVersion: `Package doesn't have a version.`,
answerRequired: 'An answer is required.',
missingWhyDependency: 'Missing package name, folder or path to file to identify why a package has been installed',
bugReport: 'If you think this is a bug, please open a bug report with the information provided in $0.',
unexpectedError: 'An unexpected error occurred: $0.',
jsonError: 'Error parsing JSON at $0, $1.',
noFilePermission: "We don't have permissions to touch the file $0.",
allDependenciesUpToDate: 'All of your dependencies are up to date.',
frozenLockfileError: 'Your lockfile needs to be updated, but yarn was run with `--frozen-lockfile`.',
fileWriteError: 'Could not write file $0: $1',
yarnOutdated: "Your current version of Yarn is out of date. The latest version is $0 while you're on $1.",
yarnOutdatedInstaller: 'To upgrade, download the latest installer at $0.',
yarnOutdatedCommand: 'To upgrade, run the following command:',
tooManyArguments: 'Too many arguments, maximum of $0.',
tooFewArguments: 'Not enough arguments, expected at least $0.',
noArguments: "This command doesn't require any arguments.",
ownerRemoving: 'Removing owner $0 from package $1.',
ownerRemoved: 'Owner removed.',
ownerRemoveError: "Couldn't remove owner.",
ownerGetting: 'Getting owners for package $0',
ownerGettingFailed: "Couldn't get list of owners.",
ownerAlready: 'This user is already an owner of this package.',
ownerAdded: 'Added owner.',
ownerAdding: 'Adding owner $0 to package $1',
ownerAddingFailed: "Couldn't add owner.",
ownerNone: 'No owners.',
teamCreating: 'Creating team',
teamRemoving: 'Removing team',
teamAddingUser: 'Adding user to team',
teamRemovingUser: 'Removing user from team',
teamListing: 'Listing teams',
cleaning: 'Cleaning modules',
cleanCreatingFile: 'Creating $0',
binLinkCollision: "There's already a linked binary called $0 in your global Yarn bin. Could not link this package's $0 bin entry.",
linkCollision: "There's already a module called $0 registered.",
linkMissing: 'No registered module found called $0.',
linkInstallMessage: 'You can now run `yarn link $0` in the projects where you want to use this module and it will be used instead.',
linkRegistered: 'Registered $0.',
linkUnregistered: 'Unregistered $0.',
linkUsing: 'Using linked module for $0.',
commandNotSpecified: 'No command specified.',
binCommands: 'Commands available from binary scripts: ',
possibleCommands: 'Project commands',
commandQuestion: 'Which command would you like to run?',
commandFailed: 'Command failed with exit code $0.',
foundIncompatible: 'Found incompatible module',
incompatibleEngine: 'The engine $0 is incompatible with this module. Expected version $1.',
incompatibleCPU: 'The CPU architecture $0 is incompatible with this module.',
incompatibleOS: 'The platform $0 is incompatible with this module.',
invalidEngine: 'The engine $0 appears to be invalid.',
selfUpdateReleased: 'Replaced current release with $0.',
selfUpdateDownloading: 'Downloading yarn version $0.',
selfUpdateNoNewer: 'Yarn is already using the latest version.',
optionalCompatibilityExcluded: '$0 is an optional dependency and failed compatibility check. Excluding it from installation.',
optionalModuleFail: 'This module is OPTIONAL, you can safely ignore this error',
optionalModuleScriptFail: 'Error running install script for optional dependency: $0',
optionalModuleCleanupFail: 'Could not cleanup build artifacts from failed install: $0',
unmetPeer: '$0 has unmet peer dependency $1.',
incorrectPeer: '$0 has incorrect peer dependency $1.',
savedNewDependency: 'Saved 1 new dependency.',
savedNewDependencies: 'Saved $0 new dependencies.',
foundWarnings: 'Found $0 warnings.',
foundErrors: 'Found $0 errors.',
savedLockfile: 'Saved lockfile.',
noRequiredLockfile: 'No lockfile in this directory. Run `yarn install` to generate one.',
noLockfileFound: 'No lockfile found.',
invalidSemver: 'Invalid semver version',
newVersion: 'New version',
currentVersion: 'Current version',
manualVersionResolution: 'Unable to find a suitable version for $0, please choose one by typing one of the numbers below:',
manualVersionResolutionOption: '$0 which resolved to $1',
createdTag: 'Created tag.',
createdTagFail: "Couldn't add tag.",
deletedTag: 'Deleted tag.',
deletedTagFail: "Couldn't delete tag.",
gettingTags: 'Getting tags',
deletingTags: 'Deleting tag',
creatingTag: 'Creating tag $0 = $1',
whyStart: 'Why do we have the module $0?',
whyFinding: 'Finding dependency',
whyCalculating: 'Calculating file sizes',
whyUnknownMatch: "We couldn't find a match!",
whyInitGraph: 'Initialising dependency graph',
whyWhoKnows: "We don't know why this module exists",
whyDiskSizeWithout: 'Disk size without dependencies: $0',
whyDiskSizeUnique: 'Disk size with unique dependencies: $0',
whyDiskSizeTransitive: 'Disk size with transitive dependencies: $0',
whySharedDependencies: 'Amount of shared dependencies: $0',
whyHoistedTo: `Has been hoisted to $0`,
whyHoistedFromSimple: `This module exists because it's hoisted from $0.`,
whyDependedOnSimple: `This module exists because $0 depends on it.`,
whySpecifiedSimple: `This module exists because it's specified in $0.`,
whyReasons: 'Reasons this module exists',
whyHoistedFrom: 'Hoisted from $0',
whyDependedOn: '$0 depends on it',
whySpecified: `Specified in $0`,
uninstalledPackages: 'Uninstalled packages.',
uninstallRegenerate: 'Regenerating lockfile and installing missing dependencies',
cleanRemovedFiles: 'Removed $0 files',
cleanSavedSize: 'Saved $0 MB.',
npmUsername: 'npm username',
npmPassword: 'npm password',
npmEmail: 'npm email',
loggingIn: 'Logging in',
loggedIn: 'Logged in.',
notRevokingEnvToken: 'Not revoking login token, specified via environment variable.',
notRevokingConfigToken: 'Not revoking login token, specified via config file.',
noTokenToRevoke: 'No login token to revoke.',
revokingToken: 'Revoking token',
revokedToken: 'Revoked login token.',
loginAsPublic: 'Logging in as public',
incorrectCredentials: 'Incorrect username or password.',
clearedCredentials: 'Cleared login credentials.',
publishSame: 'New version is the same as the current version.',
publishFail: "Couldn't publish package.",
publishPrivate: 'Package marked as private, not publishing.',
published: 'Published.',
publishing: 'Publishing',
infoFail: 'Received invalid response from npm.',
malformedRegistryResponse: 'Received malformed response from registry for $0. The registry may be down.',
cantRequestOffline: 'Can\'t make a request in offline mode',
requestManagerNotSetupHAR: 'RequestManager was not setup to capture HAR files',
requestError: 'Request $0 returned a $1',
requestFailed: 'Request failed $0',
tarballNotInNetworkOrCache: '$0: Tarball is not in network and can not be located in cache ($1)',
fetchBadHash: 'Bad hash. Expected $0 but got $1 ',
fetchErrorCorrupt: '$0. Mirror tarball appears to be corrupt. You can resolve this by running:\n\n rm -rf $1\n yarn install',
errorDecompressingTarball: '$0. Error decompressing $1, it appears to be corrupt.',
updateInstalling: 'Installing $0...',
hostedGitResolveError: 'Error connecting to repository. Please, check the url.',
unknownFetcherFor: 'Unknown fetcher for $0',
refusingDownloadGitWithoutCommit: 'Refusing to download the git repo $0 over plain git without a commit hash',
refusingDownloadHTTPWithoutCommit: 'Refusing to download the git repo $0 over HTTP without a commit hash',
refusingDownloadHTTPSWithoutCommit: 'Refusing to download the git repo $0 over HTTPS without a commit hash - possible certificate error?',
packageInstalledWithBinaries: 'Installed $0 with binaries:',
packageHasBinaries: '$0 has binaries:',
packageHasNoBinaries: '$0 has no binaries',
couldBeDeduped: '$0 could be deduped from $1 to $2',
lockfileNotContainPatter: 'Lockfile does not contain pattern: $0',
integrityHashesDontMatch: 'Integrity hashes don\'t match, expected $0 but got $1',
noIntegirtyHashFile: 'Couldn\'t find an integrity hash file',
packageNotInstalled: '$0 not installed',
optionalDepNotInstalled: 'Optional dependency $0 not installed',
packageWrongVersion: '$0 is wrong version: expected $1, got $2',
packageDontSatisfy: '$0 doesn\'t satisfy found match of $1',
lockfileExists: 'Lockfile already exists, not importing.',
skippingImport: 'Skipping import of $0 for $1',
importFailed: 'Import of $0 for $1 failed, resolving normally.',
importResolveFailed: 'Import of $0 failed starting in $1',
importResolvedRangeMatch: 'Using version $0 of $1 instead of $2 for $3'
};
exports.default = messages;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| base-resolver.js | 13.33% | (2 / 15) | 100% | (0 / 0) | 0% | (0 / 3) | 13.33% | (2 / 15) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
class BaseResolver {
constructor(request, fragment) {
this.resolver = request.resolver;
this.reporter = request.reporter;
this.fragment = fragment;
this.registry = request.registry;
this.request = request;
this.pattern = request.pattern;
this.config = request.config;
}
fork(Resolver, resolveArg) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
const resolver = new (Function.prototype.bind.apply(Resolver, [null].concat([this.request], args)))();
resolver.registry = this.registry;
return resolver.resolve(resolveArg);
}
resolve() {
throw new Error('Not implemented');
}
}
exports.default = BaseResolver;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| bitbucket-resolver.js | 69.23% | (9 / 13) | 62.5% | (5 / 8) | 33.33% | (2 / 6) | 66.67% | (8 / 12) | |
| exotic-resolver.js | 63.64% | (7 / 11) | 62.5% | (5 / 8) | 66.67% | (2 / 3) | 60% | (6 / 10) | |
| file-resolver.js | 31.08% | (23 / 74) | 9.43% | (5 / 53) | 15.38% | (2 / 13) | 34.38% | (22 / 64) | |
| gist-resolver.js | 42.5% | (17 / 40) | 20.83% | (5 / 24) | 22.22% | (2 / 9) | 53.33% | (16 / 30) | |
| github-resolver.js | 50% | (9 / 18) | 41.67% | (5 / 12) | 28.57% | (2 / 7) | 47.06% | (8 / 17) | |
| gitlab-resolver.js | 69.23% | (9 / 13) | 62.5% | (5 / 8) | 33.33% | (2 / 6) | 66.67% | (8 / 12) | |
| hosted-git-resolver.js | 15.32% | (19 / 124) | 6.76% | (5 / 74) | 8% | (2 / 25) | 14.63% | (18 / 123) | |
| registry-resolver.js | 50% | (9 / 18) | 41.67% | (5 / 12) | 40% | (2 / 5) | 47.06% | (8 / 17) | |
| tarball-resolver.js | 30.26% | (23 / 76) | 11.36% | (5 / 44) | 14.29% | (2 / 14) | 33.33% | (22 / 66) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _hostedGitResolver;
function _load_hostedGitResolver() {
return _hostedGitResolver = _interopRequireDefault(require('./hosted-git-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class BitbucketResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default {
static getTarballUrl(parts, hash) {
return `https://${this.hostname}/${parts.user}/${parts.repo}/get/${hash}.tar.gz`;
}
static getGitHTTPUrl(parts) {
return `https://${this.hostname}/${parts.user}/${parts.repo}.git`;
}
static getGitSSHUrl(parts) {
return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`;
}
static getHTTPFileUrl(parts, filename, commit) {
return `https://${this.hostname}/${parts.user}/${parts.repo}/raw/${commit}/${filename}`;
}
}
exports.default = BitbucketResolver;
BitbucketResolver.hostname = 'bitbucket.org';
BitbucketResolver.protocol = 'bitbucket';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _baseResolver;
function _load_baseResolver() {
return _baseResolver = _interopRequireDefault(require('../base-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class ExoticResolver extends (_baseResolver || _load_baseResolver()).default {
static isVersion(pattern) {
const proto = this.protocol;
if (proto) {
return pattern.startsWith(`${proto}:`);
} else {
throw new Error('No protocol specified');
}
}
}
exports.default = ExoticResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _assign;
function _load_assign() {
return _assign = _interopRequireDefault(require('babel-runtime/core-js/object/assign'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
var _misc;
function _load_misc() {
return _misc = _interopRequireWildcard(require('../../util/misc.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const path = require('path');
class FileResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
this.loc = (_misc || _load_misc()).removePrefix(fragment, 'file:');
}
resolve() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
let loc = _this.loc;
if (!path.isAbsolute(loc)) {
loc = path.join(_this.config.cwd, loc);
}
if (!(yield (_fs || _load_fs()).exists(loc))) {
throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('doesntExist', loc));
}
const manifest = yield _this.config.readManifest(loc, _this.registry);
const registry = manifest._registry;
invariant(registry, 'expected registry');
manifest._remote = {
type: 'copy',
registry: registry,
hash: null,
reference: loc
};
manifest._uid = manifest.version;
// Normalize relative paths; if anything changes, make a copy of the manifest
const dependencies = _this.normalizeDependencyPaths(manifest.dependencies, loc);
const optionalDependencies = _this.normalizeDependencyPaths(manifest.optionalDependencies, loc);
if (dependencies !== manifest.dependencies || optionalDependencies !== manifest.optionalDependencies) {
const _manifest = (0, (_assign || _load_assign()).default)({}, manifest);
if (dependencies != null) {
_manifest.dependencies = dependencies;
}
if (optionalDependencies != null) {
_manifest.optionalDependencies = optionalDependencies;
}
return _manifest;
} else {
return manifest;
}
})();
}
normalizeDependencyPaths(section, loc) {
if (section == null) {
return section;
}
let temp = section;
for (const _ref of (_misc || _load_misc()).entries(section)) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const k = _ref2[0];
const v = _ref2[1];
if (typeof v === 'string' && v.startsWith('file:') && !path.isAbsolute(v)) {
if (temp === section) {
temp = (0, (_assign || _load_assign()).default)({}, section);
}
temp[k] = `file:${path.relative(this.config.cwd, path.join(loc, (_misc || _load_misc()).removePrefix(v, 'file:')))}`;
}
}
return temp;
}
}
exports.default = FileResolver;
FileResolver.protocol = 'file';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.explodeGistFragment = explodeGistFragment;
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _gitResolver;
function _load_gitResolver() {
return _gitResolver = _interopRequireDefault(require('./git-resolver.js'));
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
var _misc;
function _load_misc() {
return _misc = _interopRequireWildcard(require('../../util/misc.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function explodeGistFragment(fragment, reporter) {
fragment = (_misc || _load_misc()).removePrefix(fragment, 'gist:');
const parts = fragment.split('#');
if (parts.length <= 2) {
return {
id: parts[0],
hash: parts[1] || ''
};
} else {
throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidGistFragment', fragment));
}
}
class GistResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
var _explodeGistFragment = explodeGistFragment(fragment, this.reporter);
const id = _explodeGistFragment.id,
hash = _explodeGistFragment.hash;
this.id = id;
this.hash = hash;
}
resolve() {
return this.fork((_gitResolver || _load_gitResolver()).default, false, `https://gist.github.com/${this.id}.git#${this.hash}`);
}
}
exports.default = GistResolver;
GistResolver.protocol = 'gist';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _hostedGitResolver;
function _load_hostedGitResolver() {
return _hostedGitResolver = _interopRequireDefault(require('./hosted-git-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class GitHubResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default {
static isVersion(pattern) {
// github proto
if (pattern.startsWith('github:')) {
return true;
}
// github shorthand
if (/^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(pattern)) {
return true;
}
return false;
}
static getTarballUrl(parts, hash) {
return `https://codeload.${this.hostname}/${parts.user}/${parts.repo}/tar.gz/${hash}`;
}
static getGitSSHUrl(parts) {
return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`;
}
static getGitHTTPUrl(parts) {
return `https://${this.hostname}/${parts.user}/${parts.repo}.git`;
}
static getHTTPFileUrl(parts, filename, commit) {
return `https://raw.githubusercontent.com/${parts.user}/${parts.repo}/${commit}/${filename}`;
}
}
exports.default = GitHubResolver;
GitHubResolver.protocol = 'github';
GitHubResolver.hostname = 'github.com';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _hostedGitResolver;
function _load_hostedGitResolver() {
return _hostedGitResolver = _interopRequireDefault(require('./hosted-git-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class GitLabResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default {
static getTarballUrl(parts, hash) {
return `https://${this.hostname}/${parts.user}/${parts.repo}/repository/archive.tar.gz?ref=${hash}`;
}
static getGitHTTPUrl(parts) {
return `https://${this.hostname}/${parts.user}/${parts.repo}.git`;
}
static getGitSSHUrl(parts) {
return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`;
}
static getHTTPFileUrl(parts, filename, commit) {
return `https://${this.hostname}/${parts.user}/${parts.repo}/raw/${commit}/${filename}`;
}
}
exports.default = GitLabResolver;
GitLabResolver.hostname = 'gitlab.com';
GitLabResolver.protocol = 'gitlab';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
exports.explodeHostedGitFragment = explodeHostedGitFragment;
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _index;
function _load_index() {
return _index = require('../../registries/index.js');
}
var _gitResolver;
function _load_gitResolver() {
return _gitResolver = _interopRequireDefault(require('./git-resolver.js'));
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
var _git;
function _load_git() {
return _git = _interopRequireDefault(require('../../util/git.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function explodeHostedGitFragment(fragment, reporter) {
const preParts = fragment.split('@');
if (preParts.length > 2) {
fragment = preParts[1] + '@' + preParts[2];
}
const parts = fragment.split(':');
if (parts.length == 3) {
// protocol + host + folder
parts[1] = parts[1].indexOf('//') >= 0 ? parts[1].substr(2) : parts[1];
fragment = parts[1] + '/' + parts[2];
} else if (parts.length == 2) {
if (parts[0].indexOf('@') == -1) {
// protocol + host
fragment = parts[1];
} else {
// host + folder
fragment = parts[0] + '/' + parts[1];
}
} else if (parts.length == 1) {
fragment = parts[0];
} else {
throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidHostedGitFragment', fragment));
}
const userParts = fragment.split('/');
if (userParts.length >= 2) {
if (userParts[0].indexOf('@') >= 0) {
userParts.shift();
}
const user = userParts.shift();
const repoParts = userParts.join('/').split(/(?:[.]git)?#(.*)/);
if (repoParts.length <= 3) {
return {
user: user,
repo: repoParts[0].replace('.git', ''),
hash: repoParts[1] || ''
};
}
}
throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidHostedGitFragment', fragment));
}
class HostedGitResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
const exploded = this.exploded = explodeHostedGitFragment(fragment, this.reporter);
const user = exploded.user,
repo = exploded.repo,
hash = exploded.hash;
this.user = user;
this.repo = repo;
this.hash = hash;
}
static getTarballUrl(exploded, commit) {
exploded;
commit;
throw new Error('Not implemented');
}
static getGitHTTPUrl(exploded) {
exploded;
throw new Error('Not implemented');
}
static getGitSSHUrl(exploded) {
exploded;
throw new Error('Not implemented');
}
static getHTTPFileUrl(exploded, filename, commit) {
exploded;
filename;
commit;
throw new Error('Not implemented');
}
getRefOverHTTP(url) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const client = new (_git || _load_git()).default(_this.config, url, _this.hash);
let out = yield _this.config.requestManager.request({
url: `${url}/info/refs?service=git-upload-pack`,
queue: _this.resolver.fetchingQueue
});
if (out) {
// clean up output
let lines = out.trim().split('\n');
// remove first two lines which contains compatibility info etc
lines = lines.slice(2);
// remove last line which contains the terminator "0000"
lines.pop();
// remove line lengths from start of each line
lines = lines.map(function (line) {
return line.slice(4);
});
out = lines.join('\n');
} else {
throw new Error(_this.reporter.lang('hostedGitResolveError'));
}
const refs = (_git || _load_git()).default.parseRefs(out);
return yield client.setRef(refs);
})();
}
resolveOverHTTP(url) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const shrunk = _this2.request.getLocked('tarball');
if (shrunk) {
return shrunk;
}
const commit = yield _this2.getRefOverHTTP(url);
const config = _this2.config;
const tryRegistry = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (registry) {
const filename = (_index || _load_index()).registries[registry].filename;
const href = _this2.constructor.getHTTPFileUrl(_this2.exploded, filename, commit);
const file = yield config.requestManager.request({
url: href,
queue: _this2.resolver.fetchingQueue
});
if (!file) {
return null;
}
const tarballUrl = _this2.constructor.getTarballUrl(_this2.exploded, commit);
const json = yield config.readJson(href, function () {
return JSON.parse(file);
});
json._uid = commit;
json._remote = {
resolved: tarballUrl,
type: 'tarball',
reference: tarballUrl,
registry: registry
};
return json;
});
return function tryRegistry(_x) {
return _ref.apply(this, arguments);
};
})();
const file = yield tryRegistry(_this2.registry);
if (file) {
return file;
}
for (const registry in (_index || _load_index()).registries) {
if (registry === _this2.registry) {
continue;
}
const file = yield tryRegistry(registry);
if (file) {
return file;
}
}
throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('couldntFindManifestIn', url));
})();
}
hasHTTPCapability(url) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
return (yield _this3.config.requestManager.request({
url: url,
method: 'HEAD',
queue: _this3.resolver.fetchingQueue,
followRedirect: false
})) !== false;
})();
}
resolve() {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const httpUrl = _this4.constructor.getGitHTTPUrl(_this4.exploded);
const sshUrl = _this4.constructor.getGitSSHUrl(_this4.exploded);
// If we can access the files over HTTP then we should as it's MUCH faster than git
// archive and tarball unarchiving. The HTTP API is only available for public repos
// though.
if (yield _this4.hasHTTPCapability(httpUrl)) {
return yield _this4.resolveOverHTTP(httpUrl);
}
// If the url is accessible over git archive then we should immediately delegate to
// the git resolver.
//
// NOTE: Here we use a different url than when we delegate to the git resolver later on.
// This is because `git archive` requires access over ssh and github only allows that
// if you have write permissions
if (yield (_git || _load_git()).default.hasArchiveCapability(sshUrl)) {
const archiveClient = new (_git || _load_git()).default(_this4.config, sshUrl, _this4.hash);
const commit = yield archiveClient.init();
return yield _this4.fork((_gitResolver || _load_gitResolver()).default, true, `${sshUrl}#${commit}`);
}
// fallback to the plain git resolver
return yield _this4.fork((_gitResolver || _load_gitResolver()).default, true, sshUrl);
})();
}
}
exports.default = HostedGitResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class RegistryResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
const match = fragment.match(/^(\S+):(.*?)(@(.*?)|)$/);
if (match) {
this.range = match[4] || 'latest';
this.name = match[2];
} else {
throw new (_errors || _load_errors()).MessageError(this.reporter.lang('invalidFragment', fragment));
}
// $FlowFixMe
this.registry = this.constructor.protocol;
}
resolve() {
return this.fork(this.constructor.factory, false, this.name, this.range);
}
}
exports.default = RegistryResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _tarballFetcher;
function _load_tarballFetcher() {
return _tarballFetcher = _interopRequireDefault(require('../../fetchers/tarball-fetcher.js'));
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
var _gitResolver;
function _load_gitResolver() {
return _gitResolver = _interopRequireDefault(require('./git-resolver.js'));
}
var _misc;
function _load_misc() {
return _misc = require('../../util/misc.js');
}
var _version;
function _load_version() {
return _version = _interopRequireWildcard(require('../../util/version.js'));
}
var _crypto;
function _load_crypto() {
return _crypto = _interopRequireWildcard(require('../../util/crypto.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
class TarballResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
var _versionUtil$explodeH = (_version || _load_version()).explodeHashedUrl(fragment);
const hash = _versionUtil$explodeH.hash,
url = _versionUtil$explodeH.url;
this.hash = hash;
this.url = url;
}
static isVersion(pattern) {
// we can sometimes match git urls which we don't want
if ((_gitResolver || _load_gitResolver()).default.isVersion(pattern)) {
return false;
}
// full http url
if (pattern.startsWith('http://') || pattern.startsWith('https://')) {
return true;
}
// local file reference - ignore patterns with names
if (pattern.indexOf('@') < 0) {
if (pattern.endsWith('.tgz') || pattern.endsWith('.tar.gz')) {
return true;
}
}
return false;
}
resolve() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const shrunk = _this.request.getLocked('tarball');
if (shrunk) {
return shrunk;
}
const url = (0, (_misc || _load_misc()).removePrefix)(_this.url, 'file:');
let hash = _this.hash,
registry = _this.registry;
let pkgJson;
// generate temp directory
const dest = _this.config.getTemp((_crypto || _load_crypto()).hash(url));
if (yield _this.config.isValidModuleDest(dest)) {
var _ref = yield _this.config.readPackageMetadata(dest);
// load from local cache
pkgJson = _ref.package;
hash = _ref.hash;
registry = _ref.registry;
} else {
// delete if invalid
yield (_fs || _load_fs()).unlink(dest);
const fetcher = new (_tarballFetcher || _load_tarballFetcher()).default(dest, {
type: 'tarball',
reference: url,
registry: registry,
hash: hash
}, _this.config, false);
// fetch file and get it's hash
const fetched = yield fetcher.fetch();
pkgJson = fetched.package;
hash = fetched.hash;
registry = pkgJson._registry;
invariant(registry, 'expected registry');
}
// use the commit/tarball hash as the uid as we can't rely on the version as it's not
// in the registry
pkgJson._uid = hash;
// set remote so it can be "fetched"
pkgJson._remote = {
type: 'copy',
resolved: `${url}#${hash}`,
hash: hash,
registry: registry,
reference: dest
};
return pkgJson;
})();
}
}
exports.default = TarballResolver;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| npm-resolver.js | 22.73% | (30 / 132) | 4.55% | (5 / 110) | 9.52% | (2 / 21) | 23.77% | (29 / 122) | |
| registry-resolver.js | 63.64% | (7 / 11) | 83.33% | (5 / 6) | 66.67% | (2 / 3) | 60% | (6 / 10) | |
| yarn-resolver.js | 100% | (7 / 7) | 83.33% | (5 / 6) | 100% | (2 / 2) | 100% | (6 / 6) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _assign;
function _load_assign() {
return _assign = _interopRequireDefault(require('babel-runtime/core-js/object/assign'));
}
var _keys;
function _load_keys() {
return _keys = _interopRequireDefault(require('babel-runtime/core-js/object/keys'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _registryResolver;
function _load_registryResolver() {
return _registryResolver = _interopRequireDefault(require('./registry-resolver.js'));
}
var _npmRegistry;
function _load_npmRegistry() {
return _npmRegistry = _interopRequireDefault(require('../../registries/npm-registry.js'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('../../util/map.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _constants;
function _load_constants() {
return _constants = require('../../constants.js');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const inquirer = require('inquirer');
const tty = require('tty');
const invariant = require('invariant');
const path = require('path');
const NPM_REGISTRY = /http[s]:\/\/registry.npmjs.org/g;
class NpmResolver extends (_registryResolver || _load_registryResolver()).default {
static findVersionInRegistryResponse(config, range, body, request) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (!body['dist-tags']) {
throw new (_errors || _load_errors()).MessageError(config.reporter.lang('malformedRegistryResponse', body.name));
}
if (range in body['dist-tags']) {
range = body['dist-tags'][range];
}
const satisfied = yield config.resolveConstraints((0, (_keys || _load_keys()).default)(body.versions), range);
if (satisfied) {
return body.versions[satisfied];
} else if (request && !config.nonInteractive) {
if (request.resolver && request.resolver.activity) {
request.resolver.activity.end();
}
config.reporter.log(config.reporter.lang('couldntFindVersionThatMatchesRange', body.name, range));
let pageSize;
if (process.stdout instanceof tty.WriteStream) {
pageSize = process.stdout.rows - 2;
}
const response = yield inquirer.prompt([{
name: 'package',
type: 'list',
message: config.reporter.lang('chooseVersionFromList'),
choices: (0, (_keys || _load_keys()).default)(body.versions).reverse(),
pageSize: pageSize
}]);
if (response && response.package) {
return body.versions[response.package];
}
}
throw new (_errors || _load_errors()).MessageError(config.reporter.lang('couldntFindVersionThatMatchesRange', body.name, range));
})();
}
resolveRequest() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (_this.config.offline) {
const res = _this.resolveRequestOffline();
if (res != null) {
return res;
}
}
const body = yield _this.config.registries.npm.request((_npmRegistry || _load_npmRegistry()).default.escapeName(_this.name));
if (body) {
return yield NpmResolver.findVersionInRegistryResponse(_this.config, _this.range, body, _this.request);
} else {
return null;
}
})();
}
resolveRequestOffline() {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const scope = _this2.config.registries.npm.getScope(_this2.name);
// find modules of this name
const prefix = scope ? _this2.name.split(/\/|%2f/)[1] : `npm-${_this2.name}-`;
invariant(_this2.config.cacheFolder, 'expected packages root');
const cacheFolder = path.join(_this2.config.cacheFolder, scope ? 'npm-' + scope : '');
const files = yield _this2.config.getCache('cachedPackages', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const files = yield (_fs || _load_fs()).readdir(cacheFolder);
const validFiles = [];
for (const name of files) {
// no hidden files
if (name[0] === '.') {
continue;
}
// ensure valid module cache
const dir = path.join(cacheFolder, name);
if (yield _this2.config.isValidModuleDest(dir)) {
validFiles.push(name);
}
}
return validFiles;
}));
const versions = (0, (_map || _load_map()).default)();
for (const name of files) {
// check if folder starts with our prefix
if (name.indexOf(prefix) !== 0) {
continue;
}
const dir = path.join(cacheFolder, name);
// read manifest and validate correct name
const pkg = yield _this2.config.readManifest(dir, 'npm');
if (pkg.name !== _this2.name) {
continue;
}
// read package metadata
const metadata = yield _this2.config.readPackageMetadata(dir);
if (!metadata.remote) {
continue; // old yarn metadata
}
versions[pkg.version] = (0, (_assign || _load_assign()).default)({}, pkg, { _remote: metadata.remote });
}
const satisfied = yield _this2.config.resolveConstraints((0, (_keys || _load_keys()).default)(versions), _this2.range);
if (satisfied) {
return versions[satisfied];
} else if (!_this2.config.preferOffline) {
throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('couldntFindPackageInCache', _this2.name, _this2.range, (0, (_keys || _load_keys()).default)(versions).join(', ')));
} else {
return null;
}
})();
}
cleanRegistry(url) {
if (this.config.getOption('registry') === (_constants || _load_constants()).YARN_REGISTRY) {
return url.replace(NPM_REGISTRY, (_constants || _load_constants()).YARN_REGISTRY);
} else {
return url;
}
}
resolve() {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// lockfile
const shrunk = _this3.request.getLocked('tarball');
if (shrunk) {
return shrunk;
}
const info = yield _this3.resolveRequest();
if (info == null) {
throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('packageNotFoundRegistry', _this3.name, 'npm'));
}
const deprecated = info.deprecated,
dist = info.dist;
if (typeof deprecated === 'string') {
let human = `${info.name}@${info.version}`;
const parentNames = _this3.request.getParentNames();
if (parentNames.length) {
human = parentNames.concat(human).join(' > ');
}
_this3.reporter.warn(`${human}: ${deprecated}`);
}
if (dist != null && dist.tarball) {
info._remote = {
resolved: `${_this3.cleanRegistry(dist.tarball)}#${dist.shasum}`,
type: 'tarball',
reference: _this3.cleanRegistry(dist.tarball),
hash: dist.shasum,
registry: 'npm'
};
}
info._uid = info.version;
return info;
})();
}
}
exports.default = NpmResolver;
NpmResolver.registry = 'npm';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _baseResolver;
function _load_baseResolver() {
return _baseResolver = _interopRequireDefault(require('../base-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class RegistryResolver extends (_baseResolver || _load_baseResolver()).default {
constructor(request, name, range) {
super(request, `${name}@${range}`);
this.name = name;
this.range = range;
this.registryConfig = request.config.registries[this.constructor.registry].config;
}
}
exports.default = RegistryResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _npmResolver;
function _load_npmResolver() {
return _npmResolver = _interopRequireDefault(require('./npm-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class YarnResolver extends (_npmResolver || _load_npmResolver()).default {}
exports.default = YarnResolver;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| blocking-queue.js | 32.43% | (24 / 74) | 22.73% | (10 / 44) | 21.43% | (3 / 14) | 31.51% | (23 / 73) | |
| child.js | 38.36% | (28 / 73) | 23.08% | (12 / 52) | 45.45% | (5 / 11) | 40.32% | (25 / 62) | |
| crypto.js | 37.5% | (6 / 16) | 0% | (0 / 6) | 0% | (0 / 5) | 37.5% | (6 / 16) | |
| env-replace.js | 30.77% | (4 / 13) | 0% | (0 / 16) | 0% | (0 / 1) | 30.77% | (4 / 13) | |
| execute-lifecycle-script.js | 32.26% | (50 / 155) | 7.41% | (8 / 108) | 7.69% | (2 / 26) | 33.79% | (49 / 145) | |
| filter.js | 20.83% | (15 / 72) | 0% | (0 / 61) | 0% | (0 / 6) | 21.13% | (15 / 71) | |
| fix-cmd-win-slashes.js | 22.73% | (5 / 22) | 0% | (0 / 8) | 0% | (0 / 3) | 22.73% | (5 / 22) | |
| fs.js | 22.1% | (103 / 466) | 12.8% | (37 / 289) | 5.19% | (4 / 77) | 22.37% | (102 / 456) | |
| map.js | 88.89% | (16 / 18) | 84.21% | (16 / 19) | 100% | (3 / 3) | 88.24% | (15 / 17) | |
| misc.js | 38.1% | (16 / 42) | 0% | (0 / 12) | 0% | (0 / 7) | 38.1% | (16 / 42) | |
| mutex.js | 50% | (10 / 20) | 41.67% | (5 / 12) | 66.67% | (2 / 3) | 56.25% | (9 / 16) | |
| network.js | 75% | (15 / 20) | 50% | (3 / 6) | 100% | (1 / 1) | 75% | (15 / 20) | |
| parse-package-name.js | 58.33% | (7 / 12) | 0% | (0 / 6) | 0% | (0 / 3) | 63.64% | (7 / 11) | |
| promise.js | 24.56% | (14 / 57) | 0% | (0 / 28) | 9.09% | (1 / 11) | 25% | (14 / 56) | |
| request-manager.js | 14.22% | (29 / 204) | 6.99% | (10 / 143) | 19.05% | (4 / 21) | 13.54% | (26 / 192) | |
| stream.js | 17.07% | (7 / 41) | 0% | (0 / 7) | 0% | (0 / 6) | 17.5% | (7 / 40) | |
| user-home-dir.js | 100% | (6 / 6) | 75% | (3 / 4) | 100% | (0 / 0) | 100% | (6 / 6) | |
| version.js | 60% | (3 / 5) | 0% | (0 / 2) | 0% | (0 / 1) | 60% | (3 / 5) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _keys;
function _load_keys() {
return _keys = _interopRequireDefault(require('babel-runtime/core-js/object/keys'));
}
var _stringify;
function _load_stringify() {
return _stringify = _interopRequireDefault(require('babel-runtime/core-js/json/stringify'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('./map.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const debug = require('debug')('yarn');
class BlockingQueue {
constructor(alias) {
let maxConcurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity;
this.concurrencyQueue = [];
this.maxConcurrency = maxConcurrency;
this.runningCount = 0;
this.warnedStuck = false;
this.alias = alias;
this.first = true;
this.running = (0, (_map || _load_map()).default)();
this.queue = (0, (_map || _load_map()).default)();
this.stuckTick = this.stuckTick.bind(this);
}
stillActive() {
if (this.stuckTimer) {
clearTimeout(this.stuckTimer);
}
this.stuckTimer = setTimeout(this.stuckTick, 5000);
}
stuckTick() {
if (this.runningCount === 1) {
this.warnedStuck = true;
debug(`The ${(0, (_stringify || _load_stringify()).default)(this.alias)} blocking queue may be stuck. 5 seconds ` + `without any activity with 1 worker: ${(0, (_keys || _load_keys()).default)(this.running)[0]}`);
}
}
push(key, factory) {
if (this.first) {
this.first = false;
} else {
this.stillActive();
}
return new (_promise || _load_promise()).default((resolve, reject) => {
// we're already running so push ourselves to the queue
const queue = this.queue[key] = this.queue[key] || [];
queue.push({ factory: factory, resolve: resolve, reject: reject });
if (!this.running[key]) {
this.shift(key);
}
});
}
shift(key) {
if (this.running[key]) {
delete this.running[key];
this.runningCount--;
if (this.warnedStuck) {
this.warnedStuck = false;
debug(`${(0, (_stringify || _load_stringify()).default)(this.alias)} blocking queue finally resolved. Nothing to worry about.`);
}
}
const queue = this.queue[key];
if (!queue) {
return;
}
var _queue$shift = queue.shift();
const resolve = _queue$shift.resolve,
reject = _queue$shift.reject,
factory = _queue$shift.factory;
if (!queue.length) {
delete this.queue[key];
}
const next = () => {
this.shift(key);
this.shiftConcurrencyQueue();
};
const run = () => {
this.running[key] = true;
this.runningCount++;
factory().then(function (val) {
resolve(val);
next();
return null;
}).catch(function (err) {
reject(err);
next();
});
};
this.maybePushConcurrencyQueue(run);
}
maybePushConcurrencyQueue(run) {
if (this.runningCount < this.maxConcurrency) {
run();
} else {
this.concurrencyQueue.push(run);
}
}
shiftConcurrencyQueue() {
if (this.runningCount < this.maxConcurrency) {
const fn = this.concurrencyQueue.shift();
if (fn) {
fn();
}
}
}
}
exports.default = BlockingQueue;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.exec = exports.queue = undefined;
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
exports.spawn = spawn;
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _blockingQueue;
function _load_blockingQueue() {
return _blockingQueue = _interopRequireDefault(require('./blocking-queue.js'));
}
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _promise2;
function _load_promise2() {
return _promise2 = require('./promise.js');
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* global child_process$spawnOpts */
const child = require('child_process');
const queue = exports.queue = new (_blockingQueue || _load_blockingQueue()).default('child', (_constants || _load_constants()).CHILD_CONCURRENCY);
// TODO: this uid check is kinda whack
let uid = 0;
const exec = exports.exec = (0, (_promise2 || _load_promise2()).promisify)(child.exec);
function spawn(program, args) {
let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
let onData = arguments[3];
return queue.push(opts.cwd || String(++uid), () => new (_promise || _load_promise()).default((resolve, reject) => {
const proc = child.spawn(program, args, opts);
let processingDone = false;
let processClosed = false;
let err = null;
let stdout = '';
proc.on('error', err => {
if (err.code === 'ENOENT') {
reject(new (_errors || _load_errors()).MessageError(`Couldn't find the binary ${program}`));
} else {
reject(err);
}
});
function updateStdout(chunk) {
stdout += chunk;
if (onData) {
onData(chunk);
}
}
function finish() {
if (err) {
reject(err);
} else {
resolve(stdout.trim());
}
}
if (typeof opts.process === 'function') {
opts.process(proc, updateStdout, reject, function () {
if (processClosed) {
finish();
} else {
processingDone = true;
}
});
} else {
if (proc.stderr) {
proc.stderr.on('data', updateStdout);
}
if (proc.stdout) {
proc.stdout.on('data', updateStdout);
}
processingDone = true;
}
proc.on('close', code => {
if (code >= 1) {
// TODO make this output nicer
err = new (_errors || _load_errors()).SpawnError(['Command failed.', `Exit code: ${code}`, `Command: ${program}`, `Arguments: ${args.join(' ')}`, `Directory: ${opts.cwd || process.cwd()}`, `Output:\n${stdout.trim()}`].join('\n'));
err.EXIT_CODE = code;
}
if (processingDone || err) {
finish();
} else {
processClosed = true;
}
});
}));
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hash = hash;
const crypto = require('crypto');
const stream = require('stream');
function hash(content) {
let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'md5';
return crypto.createHash(type).update(content).digest('hex');
}
class HashStream extends stream.Transform {
constructor(options) {
super(options);
this._hash = crypto.createHash('sha1');
this._updated = false;
}
_transform(chunk, encoding, callback) {
this._updated = true;
this._hash.update(chunk);
callback(null, chunk);
}
getHash() {
return this._hash.digest('hex');
}
test(sum) {
return this._updated && sum === this.getHash();
}
}
exports.HashStream = HashStream;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = envReplace;
const ENV_EXPR = /(\\*)\$\{([^}]+)\}/g;
function envReplace(value) {
let env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.env;
if (typeof value !== 'string' || !value) {
return value;
}
return value.replace(ENV_EXPR, (match, esc, envVarName) => {
if (esc.length && esc.length % 2) {
return match;
}
if (undefined === env[envVarName]) {
throw new Error('Failed to replace env in config: ' + match);
}
return env[envVarName] || '';
});
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.execCommand = exports.execFromManifest = exports.executeLifecycleScript = undefined;
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _keys;
function _load_keys() {
return _keys = _interopRequireDefault(require('babel-runtime/core-js/object/keys'));
}
var _toConsumableArray2;
function _load_toConsumableArray() {
return _toConsumableArray2 = _interopRequireDefault(require('babel-runtime/helpers/toConsumableArray'));
}
var _set;
function _load_set() {
return _set = _interopRequireDefault(require('babel-runtime/core-js/set'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _stringify;
function _load_stringify() {
return _stringify = _interopRequireDefault(require('babel-runtime/core-js/json/stringify'));
}
var _assign;
function _load_assign() {
return _assign = _interopRequireDefault(require('babel-runtime/core-js/object/assign'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let makeEnv = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, cwd, config) {
const env = (0, (_assign || _load_assign()).default)({}, process.env);
env.npm_lifecycle_event = stage;
env.npm_node_execpath = env.NODE || process.execPath;
env.npm_execpath = path.join(__dirname, '..', '..', 'bin', 'yarn.js');
// Set the env to production for npm compat if production mode.
// https://github.com/npm/npm/blob/30d75e738b9cb7a6a3f9b50e971adcbe63458ed3/lib/utils/lifecycle.js#L336
if (config.production) {
env.NODE_ENV = 'production';
}
// Note: npm_config_argv environment variable contains output of nopt - command-line
// parser used by npm. Since we use other parser, we just roughly emulate it's output. (See: #684)
env.npm_config_argv = (0, (_stringify || _load_stringify()).default)({ remain: [], cooked: [config.commandName], original: [config.commandName] });
// add npm_package_*
const manifest = yield config.maybeReadManifest(cwd);
if (manifest) {
const queue = [['', manifest]];
while (queue.length) {
var _queue$pop = queue.pop(),
_queue$pop2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_queue$pop, 2);
const key = _queue$pop2[0],
val = _queue$pop2[1];
if (key[0] === '_') {
continue;
}
if (typeof val === 'object') {
for (const subKey in val) {
const completeKey = [key, subKey].filter(function (part) {
return !!part;
}).join('_');
queue.push([completeKey, val[subKey]]);
}
} else if (IGNORE_MANIFEST_KEYS.indexOf(key) < 0) {
let cleanVal = String(val);
if (cleanVal.indexOf('\n') >= 0) {
cleanVal = (0, (_stringify || _load_stringify()).default)(cleanVal);
}
env[`npm_package_${key}`] = cleanVal;
}
}
}
// add npm_config_*
const keys = new (_set || _load_set()).default([].concat((0, (_toConsumableArray2 || _load_toConsumableArray()).default)((0, (_keys || _load_keys()).default)(config.registries.yarn.config)), (0, (_toConsumableArray2 || _load_toConsumableArray()).default)((0, (_keys || _load_keys()).default)(config.registries.npm.config))));
for (const key of keys) {
if (key.match(/:_/) || IGNORE_CONFIG_KEYS.indexOf(key) >= 0) {
continue;
}
let val = config.getOption(key);
if (!val) {
val = '';
} else if (typeof val === 'number') {
val = '' + val;
} else if (typeof val !== 'string') {
val = (0, (_stringify || _load_stringify()).default)(val);
}
if (val.indexOf('\n') >= 0) {
val = (0, (_stringify || _load_stringify()).default)(val);
}
const cleanKey = key.replace(/^_+/, '');
const envKey = `npm_config_${cleanKey}`.replace(/[^a-zA-Z0-9_]/g, '_');
env[envKey] = val;
}
return env;
});
return function makeEnv(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
})();
let executeLifecycleScript = exports.executeLifecycleScript = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, config, cwd, cmd, spinner) {
// if we don't have a spinner then pipe everything to the terminal
const stdio = spinner ? undefined : 'inherit';
const env = yield makeEnv(stage, cwd, config);
// split up the path
const pathParts = (env[(_constants || _load_constants()).ENV_PATH_KEY] || '').split(path.delimiter);
// add node-gyp
pathParts.unshift(path.join(__dirname, '..', '..', 'bin', 'node-gyp-bin'));
// add .bin folders to PATH
for (const registry of (0, (_keys || _load_keys()).default)((_index || _load_index()).registries)) {
const binFolder = path.join(config.registries[registry].folder, '.bin');
pathParts.unshift(path.join(config.linkFolder, binFolder));
pathParts.unshift(path.join(cwd, binFolder));
}
// join path back together
env[(_constants || _load_constants()).ENV_PATH_KEY] = pathParts.join(path.delimiter);
// get shell
const conf = { windowsVerbatimArguments: false };
let sh = 'sh';
let shFlag = '-c';
if (process.platform === 'win32') {
// cmd or command.com
sh = process.env.comspec || 'cmd';
// d - Ignore registry AutoRun commands
// s - Strip " quote characters from command.
// c - Run Command and then terminate
shFlag = '/d /s /c';
// handle windows run scripts starting with a relative path
cmd = (0, (_fixCmdWinSlashes || _load_fixCmdWinSlashes()).fixCmdWinSlashes)(cmd);
// handle quotes properly in windows environments - https://github.com/nodejs/node/issues/5060
conf.windowsVerbatimArguments = true;
}
const stdout = yield (_child || _load_child()).spawn(sh, [shFlag, cmd], (0, (_extends2 || _load_extends()).default)({ cwd: cwd, env: env, stdio: stdio }, conf), function (data) {
if (spinner) {
const line = data.toString() // turn buffer into string
.trim() // trim whitespace
.split('\n') // split into lines
.pop() // use only the last line
.replace(/\t/g, ' '); // change tabs to spaces as they can interfere with the console
if (line) {
spinner.tick(line);
}
}
});
return { cwd: cwd, command: cmd, stdout: stdout };
});
return function executeLifecycleScript(_x4, _x5, _x6, _x7, _x8) {
return _ref2.apply(this, arguments);
};
})();
let execFromManifest = exports.execFromManifest = (() => {
var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, commandName, cwd) {
const pkg = yield config.maybeReadManifest(cwd);
if (!pkg || !pkg.scripts) {
return;
}
const cmd = pkg.scripts[commandName];
if (cmd) {
yield execCommand(commandName, config, cmd, cwd);
}
});
return function execFromManifest(_x9, _x10, _x11) {
return _ref3.apply(this, arguments);
};
})();
let execCommand = exports.execCommand = (() => {
var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, config, cmd, cwd) {
const reporter = config.reporter;
try {
reporter.command(cmd);
yield executeLifecycleScript(stage, config, cwd, cmd);
return (_promise || _load_promise()).default.resolve();
} catch (err) {
if (err instanceof (_errors || _load_errors()).SpawnError) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('commandFailed', err.EXIT_CODE));
} else {
throw err;
}
}
});
return function execCommand(_x12, _x13, _x14, _x15) {
return _ref4.apply(this, arguments);
};
})();
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _child;
function _load_child() {
return _child = _interopRequireWildcard(require('./child.js'));
}
var _index;
function _load_index() {
return _index = require('../resolvers/index.js');
}
var _fixCmdWinSlashes;
function _load_fixCmdWinSlashes() {
return _fixCmdWinSlashes = require('./fix-cmd-win-slashes.js');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
const IGNORE_MANIFEST_KEYS = ['readme'];
// We treat these configs as internal, thus not expose them to process.env.
// This helps us avoid some gyp issues when building native modules.
// See https://github.com/yarnpkg/yarn/issues/2286.
const IGNORE_CONFIG_KEYS = ['lastUpdateCheck'];
exports.default = executeLifecycleScript;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _set;
function _load_set() {
return _set = _interopRequireDefault(require('babel-runtime/core-js/set'));
}
exports.sortFilter = sortFilter;
exports.matchesFilter = matchesFilter;
exports.ignoreLinesToRegex = ignoreLinesToRegex;
var _misc;
function _load_misc() {
return _misc = require('./misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const minimatch = require('minimatch');
const path = require('path');
const WHITESPACE_RE = /^\s+$/;
function sortFilter(files, filters) {
let keepFiles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new (_set || _load_set()).default();
let possibleKeepFiles = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new (_set || _load_set()).default();
let ignoreFiles = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : new (_set || _load_set()).default();
for (const file of files) {
let keep = false;
// always keep a file if a ! pattern matches it
for (const filter of filters) {
if (filter.isNegation && matchesFilter(filter, file.basename, file.relative)) {
keep = true;
break;
}
}
//
if (keep) {
keepFiles.add(file.relative);
continue;
}
// otherwise don't keep it if a pattern matches it
keep = true;
for (const filter of filters) {
if (!filter.isNegation && matchesFilter(filter, file.basename, file.relative)) {
keep = false;
break;
}
}
if (keep) {
possibleKeepFiles.add(file.relative);
} else {
ignoreFiles.add(file.relative);
}
}
// exclude file
for (const file of possibleKeepFiles) {
const parts = path.dirname(file).split(path.sep);
while (parts.length) {
const folder = parts.join(path.sep);
if (ignoreFiles.has(folder)) {
ignoreFiles.add(file);
break;
}
parts.pop();
}
}
//
for (const file of possibleKeepFiles) {
if (!ignoreFiles.has(file)) {
keepFiles.add(file);
}
}
//
for (const file of keepFiles) {
const parts = path.dirname(file).split(path.sep);
while (parts.length) {
// deregister this folder from being ignored, any files inside
// will still be marked as ignored
ignoreFiles.delete(parts.join(path.sep));
parts.pop();
}
}
return { keepFiles: keepFiles, ignoreFiles: ignoreFiles };
}
function matchesFilter(filter, basename, loc) {
if (filter.base && filter.base !== '.') {
loc = path.relative(filter.base, loc);
}
return filter.regex.test(loc) || filter.regex.test(`/${loc}`) || filter.regex.test(basename);
}
function ignoreLinesToRegex(lines) {
let base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
return lines
// create regex
.map(line => {
// remove empty lines, comments, etc
if (line === '' || line === '!' || line[0] === '#' || WHITESPACE_RE.test(line)) {
return null;
}
let pattern = line;
let isNegation = false;
// hide the fact that it's a negation from minimatch since we'll handle this specifally
// ourselves
if (pattern[0] === '!') {
isNegation = true;
pattern = pattern.slice(1);
}
// remove trailing slash
pattern = (0, (_misc || _load_misc()).removeSuffix)(pattern, '/');
const regex = minimatch.makeRe(pattern, { nocase: true });
if (regex) {
return {
base: base,
isNegation: isNegation,
regex: regex
};
} else {
return null;
}
}).filter(Boolean);
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fixCmdWinSlashes = fixCmdWinSlashes;
function fixCmdWinSlashes(cmd) {
function findQuotes(quoteSymbol) {
const quotes = [];
const addQuote = (_, index) => {
quotes.push({ from: index, to: index + _.length });
return _;
};
const regEx = new RegExp(quoteSymbol + '.*' + quoteSymbol);
cmd.replace(regEx, addQuote);
return quotes;
}
const quotes = findQuotes('"').concat(findQuotes('\''));
function isInsideQuotes(index) {
return quotes.reduce((result, quote) => {
return result || quote.from <= index && index <= quote.to;
}, false);
}
const cmdPrePattern = '((?:^|&&|&|\\|\\||\\|)\\s*)';
const cmdPattern = '(".*?"|\'.*?\'|\\S*)';
const regExp = new RegExp(`${cmdPrePattern}${cmdPattern}`, 'g');
return cmd.replace(regExp, (whole, pre, cmd, index) => {
if ((pre[0] === '&' || pre[0] === '|') && isInsideQuotes(index)) {
return whole;
}
return pre + cmd.replace(/\//g, '\\');
});
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.makeTempDir = exports.hardlinksWork = exports.writeFilePreservingEol = exports.getFileSizeOnDisk = exports.walk = exports.symlink = exports.find = exports.readJsonAndFile = exports.readJson = exports.readFileAny = exports.hardlinkBulk = exports.copyBulk = exports.link = exports.chmod = exports.lstat = exports.exists = exports.mkdirp = exports.unlink = exports.stat = exports.access = exports.rename = exports.readdir = exports.realpath = exports.readlink = exports.writeFile = exports.readFileBuffer = exports.lockQueue = undefined;
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _set;
function _load_set() {
return _set = _interopRequireDefault(require('babel-runtime/core-js/set'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let buildActionsForCopy = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) {
//
let build = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) {
const src = data.src,
dest = data.dest;
const onFresh = data.onFresh || noop;
const onDone = data.onDone || noop;
files.add(dest);
if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {
// ignored file
return;
}
const srcStat = yield lstat(src);
let srcFiles;
if (srcStat.isDirectory()) {
srcFiles = yield readdir(src);
}
if (yield exists(dest)) {
const destStat = yield lstat(dest);
const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();
const bothFolders = srcStat.isDirectory() && destStat.isDirectory();
const bothFiles = srcStat.isFile() && destStat.isFile();
if (srcStat.mode !== destStat.mode) {
try {
yield access(dest, srcStat.mode);
} catch (err) {
// EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving
// us modes that aren't valid. investigate this, it's generally safe to proceed.
}
}
if (bothFiles && srcStat.size === destStat.size && +srcStat.mtime === +destStat.mtime) {
// we can safely assume this is the same file
onDone();
reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime));
return;
}
if (bothSymlinks) {
const srcReallink = yield readlink(src);
if (srcReallink === (yield readlink(dest))) {
// if both symlinks are the same then we can continue on
onDone();
reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));
return;
}
}
if (bothFolders) {
// mark files that aren't in this folder as possibly extraneous
const destFiles = yield readdir(dest);
invariant(srcFiles, 'src files not initialised');
for (const file of destFiles) {
if (srcFiles.indexOf(file) < 0) {
const loc = path.join(dest, file);
possibleExtraneous.add(loc);
if ((yield lstat(loc)).isDirectory()) {
for (const file of yield readdir(loc)) {
possibleExtraneous.add(path.join(loc, file));
}
}
}
}
}
}
if (srcStat.isSymbolicLink()) {
onFresh();
const linkname = yield readlink(src);
actions.push({
type: 'symlink',
dest: dest,
linkname: linkname
});
onDone();
} else if (srcStat.isDirectory()) {
reporter.verbose(reporter.lang('verboseFileFolder', dest));
yield mkdirp(dest);
const destParts = dest.split(path.sep);
while (destParts.length) {
files.add(destParts.join(path.sep));
destParts.pop();
}
// push all files to queue
invariant(srcFiles, 'src files not initialised');
let remaining = srcFiles.length;
if (!remaining) {
onDone();
}
for (const file of srcFiles) {
queue.push({
onFresh: onFresh,
src: path.join(src, file),
dest: path.join(dest, file),
onDone: function (_onDone) {
function onDone() {
return _onDone.apply(this, arguments);
}
onDone.toString = function () {
return _onDone.toString();
};
return onDone;
}(function () {
if (--remaining === 0) {
onDone();
}
})
});
}
} else if (srcStat.isFile()) {
onFresh();
actions.push({
type: 'file',
src: src,
dest: dest,
atime: srcStat.atime,
mtime: srcStat.mtime,
mode: srcStat.mode
});
onDone();
} else {
throw new Error(`unsure how to copy this: ${src}`);
}
});
return function build(_x5) {
return _ref2.apply(this, arguments);
};
})();
const artifactFiles = new (_set || _load_set()).default(events.artifactFiles || []);
const files = new (_set || _load_set()).default();
// initialise events
for (const item of queue) {
const onDone = item.onDone;
item.onDone = function () {
events.onProgress(item.dest);
if (onDone) {
onDone();
}
};
}
events.onStart(queue.length);
// start building actions
const actions = [];
// custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items
// at a time due to the requirement to push items onto the queue
while (queue.length) {
const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);
yield (_promise || _load_promise()).default.all(items.map(build));
}
// simulate the existence of some files to prevent considering them extraenous
for (const file of artifactFiles) {
if (possibleExtraneous.has(file)) {
reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));
possibleExtraneous.delete(file);
}
}
for (const loc of possibleExtraneous) {
if (files.has(loc)) {
possibleExtraneous.delete(loc);
}
}
return actions;
});
return function buildActionsForCopy(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
let buildActionsForHardlink = (() => {
var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) {
//
let build = (() => {
var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) {
const src = data.src,
dest = data.dest;
const onFresh = data.onFresh || noop;
const onDone = data.onDone || noop;
files.add(dest);
if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {
// ignored file
return;
}
const srcStat = yield lstat(src);
let srcFiles;
if (srcStat.isDirectory()) {
srcFiles = yield readdir(src);
}
const destExists = yield exists(dest);
if (destExists) {
const destStat = yield lstat(dest);
const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();
const bothFolders = srcStat.isDirectory() && destStat.isDirectory();
const bothFiles = srcStat.isFile() && destStat.isFile();
if (srcStat.mode !== destStat.mode) {
try {
yield access(dest, srcStat.mode);
} catch (err) {
// EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving
// us modes that aren't valid. investigate this, it's generally safe to proceed.
reporter.verbose(err);
}
}
// correct hardlink
if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) {
onDone();
reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino));
return;
}
if (bothSymlinks) {
const srcReallink = yield readlink(src);
if (srcReallink === (yield readlink(dest))) {
// if both symlinks are the same then we can continue on
onDone();
reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));
return;
}
}
if (bothFolders) {
// mark files that aren't in this folder as possibly extraneous
const destFiles = yield readdir(dest);
invariant(srcFiles, 'src files not initialised');
for (const file of destFiles) {
if (srcFiles.indexOf(file) < 0) {
const loc = path.join(dest, file);
possibleExtraneous.add(loc);
if ((yield lstat(loc)).isDirectory()) {
for (const file of yield readdir(loc)) {
possibleExtraneous.add(path.join(loc, file));
}
}
}
}
}
}
if (srcStat.isSymbolicLink()) {
onFresh();
const linkname = yield readlink(src);
actions.push({
type: 'symlink',
dest: dest,
linkname: linkname
});
onDone();
} else if (srcStat.isDirectory()) {
reporter.verbose(reporter.lang('verboseFileFolder', dest));
yield mkdirp(dest);
const destParts = dest.split(path.sep);
while (destParts.length) {
files.add(destParts.join(path.sep));
destParts.pop();
}
// push all files to queue
invariant(srcFiles, 'src files not initialised');
let remaining = srcFiles.length;
if (!remaining) {
onDone();
}
for (const file of srcFiles) {
queue.push({
onFresh: onFresh,
src: path.join(src, file),
dest: path.join(dest, file),
onDone: function (_onDone2) {
function onDone() {
return _onDone2.apply(this, arguments);
}
onDone.toString = function () {
return _onDone2.toString();
};
return onDone;
}(function () {
if (--remaining === 0) {
onDone();
}
})
});
}
} else if (srcStat.isFile()) {
onFresh();
actions.push({
type: 'link',
src: src,
dest: dest,
removeDest: destExists
});
onDone();
} else {
throw new Error(`unsure how to copy this: ${src}`);
}
});
return function build(_x10) {
return _ref4.apply(this, arguments);
};
})();
const artifactFiles = new (_set || _load_set()).default(events.artifactFiles || []);
const files = new (_set || _load_set()).default();
// initialise events
for (const item of queue) {
const onDone = item.onDone;
item.onDone = function () {
events.onProgress(item.dest);
if (onDone) {
onDone();
}
};
}
events.onStart(queue.length);
// start building actions
const actions = [];
// custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items
// at a time due to the requirement to push items onto the queue
while (queue.length) {
const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);
yield (_promise || _load_promise()).default.all(items.map(build));
}
// simulate the existence of some files to prevent considering them extraenous
for (const file of artifactFiles) {
if (possibleExtraneous.has(file)) {
reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));
possibleExtraneous.delete(file);
}
}
for (const loc of possibleExtraneous) {
if (files.has(loc)) {
possibleExtraneous.delete(loc);
}
}
return actions;
});
return function buildActionsForHardlink(_x6, _x7, _x8, _x9) {
return _ref3.apply(this, arguments);
};
})();
let copyBulk = exports.copyBulk = (() => {
var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) {
const events = {
onStart: _events && _events.onStart || noop,
onProgress: _events && _events.onProgress || noop,
possibleExtraneous: _events ? _events.possibleExtraneous : new (_set || _load_set()).default(),
ignoreBasenames: _events && _events.ignoreBasenames || [],
artifactFiles: _events && _events.artifactFiles || []
};
const actions = yield buildActionsForCopy(queue, events, events.possibleExtraneous, reporter);
events.onStart(actions.length);
const fileActions = actions.filter(function (action) {
return action.type === 'file';
});
const currentlyWriting = {};
yield (_promise2 || _load_promise2()).queue(fileActions, (() => {
var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) {
let writePromise;
while (writePromise = currentlyWriting[data.dest]) {
yield writePromise;
}
const cleanup = function cleanup() {
return delete currentlyWriting[data.dest];
};
return currentlyWriting[data.dest] = new (_promise || _load_promise()).default(function (resolve, reject) {
const readStream = fs.createReadStream(data.src);
const writeStream = fs.createWriteStream(data.dest, { mode: data.mode });
reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest));
readStream.on('error', reject);
writeStream.on('error', reject);
writeStream.on('open', function () {
readStream.pipe(writeStream);
});
writeStream.once('finish', function () {
fs.utimes(data.dest, data.atime, data.mtime, function (err) {
if (err) {
reject(err);
} else {
events.onProgress(data.dest);
cleanup();
resolve();
}
});
});
}).then(function (arg) {
cleanup();
return arg;
}).catch(function (arg) {
cleanup();
throw arg;
});
});
return function (_x14) {
return _ref6.apply(this, arguments);
};
})(), CONCURRENT_QUEUE_ITEMS);
// we need to copy symlinks last as they could reference files we were copying
const symlinkActions = actions.filter(function (action) {
return action.type === 'symlink';
});
yield (_promise2 || _load_promise2()).queue(symlinkActions, function (data) {
const linkname = path.resolve(path.dirname(data.dest), data.linkname);
reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));
return symlink(linkname, data.dest);
});
});
return function copyBulk(_x11, _x12, _x13) {
return _ref5.apply(this, arguments);
};
})();
let hardlinkBulk = exports.hardlinkBulk = (() => {
var _ref7 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) {
const events = {
onStart: _events && _events.onStart || noop,
onProgress: _events && _events.onProgress || noop,
possibleExtraneous: _events ? _events.possibleExtraneous : new (_set || _load_set()).default(),
artifactFiles: _events && _events.artifactFiles || [],
ignoreBasenames: []
};
const actions = yield buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter);
events.onStart(actions.length);
const fileActions = actions.filter(function (action) {
return action.type === 'link';
});
yield (_promise2 || _load_promise2()).queue(fileActions, (() => {
var _ref8 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) {
reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest));
if (data.removeDest) {
yield unlink(data.dest);
}
yield link(data.src, data.dest);
});
return function (_x18) {
return _ref8.apply(this, arguments);
};
})(), CONCURRENT_QUEUE_ITEMS);
// we need to copy symlinks last as they could reference files we were copying
const symlinkActions = actions.filter(function (action) {
return action.type === 'symlink';
});
yield (_promise2 || _load_promise2()).queue(symlinkActions, function (data) {
const linkname = path.resolve(path.dirname(data.dest), data.linkname);
reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));
return symlink(linkname, data.dest);
});
});
return function hardlinkBulk(_x15, _x16, _x17) {
return _ref7.apply(this, arguments);
};
})();
let readFileAny = exports.readFileAny = (() => {
var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (files) {
for (const file of files) {
if (yield exists(file)) {
return readFile(file);
}
}
return null;
});
return function readFileAny(_x19) {
return _ref9.apply(this, arguments);
};
})();
let readJson = exports.readJson = (() => {
var _ref10 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) {
return (yield readJsonAndFile(loc)).object;
});
return function readJson(_x20) {
return _ref10.apply(this, arguments);
};
})();
let readJsonAndFile = exports.readJsonAndFile = (() => {
var _ref11 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) {
const file = yield readFile(loc);
try {
return {
object: (0, (_map || _load_map()).default)(JSON.parse(stripBOM(file))),
content: file
};
} catch (err) {
err.message = `${loc}: ${err.message}`;
throw err;
}
});
return function readJsonAndFile(_x21) {
return _ref11.apply(this, arguments);
};
})();
let find = exports.find = (() => {
var _ref12 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (filename, dir) {
const parts = dir.split(path.sep);
while (parts.length) {
const loc = parts.concat(filename).join(path.sep);
if (yield exists(loc)) {
return loc;
} else {
parts.pop();
}
}
return false;
});
return function find(_x22, _x23) {
return _ref12.apply(this, arguments);
};
})();
let symlink = exports.symlink = (() => {
var _ref13 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) {
try {
const stats = yield lstat(dest);
if (stats.isSymbolicLink() && (yield exists(dest))) {
const resolved = yield realpath(dest);
if (resolved === src) {
return;
}
}
yield unlink(dest);
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
try {
if (process.platform === 'win32') {
// use directory junctions if possible on win32, this requires absolute paths
yield fsSymlink(src, dest, 'junction');
} else {
// use relative paths otherwise which will be retained if the directory is moved
let relative;
if (yield exists(src)) {
relative = path.relative(fs.realpathSync(path.dirname(dest)), fs.realpathSync(src));
} else {
relative = path.relative(path.dirname(dest), src);
}
yield fsSymlink(relative, dest);
}
} catch (err) {
if (err.code === 'EEXIST') {
// race condition
yield symlink(src, dest);
} else {
throw err;
}
}
});
return function symlink(_x24, _x25) {
return _ref13.apply(this, arguments);
};
})();
let walk = exports.walk = (() => {
var _ref14 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir, relativeDir) {
let ignoreBasenames = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new (_set || _load_set()).default();
let files = [];
let filenames = yield readdir(dir);
if (ignoreBasenames.size) {
filenames = filenames.filter(function (name) {
return !ignoreBasenames.has(name);
});
}
for (const name of filenames) {
const relative = relativeDir ? path.join(relativeDir, name) : name;
const loc = path.join(dir, name);
const stat = yield lstat(loc);
files.push({
relative: relative,
basename: name,
absolute: loc,
mtime: +stat.mtime
});
if (stat.isDirectory()) {
files = files.concat((yield walk(loc, relative, ignoreBasenames)));
}
}
return files;
});
return function walk(_x27, _x28) {
return _ref14.apply(this, arguments);
};
})();
let getFileSizeOnDisk = exports.getFileSizeOnDisk = (() => {
var _ref15 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) {
const stat = yield lstat(loc);
const size = stat.size,
blockSize = stat.blksize;
return Math.ceil(size / blockSize) * blockSize;
});
return function getFileSizeOnDisk(_x29) {
return _ref15.apply(this, arguments);
};
})();
let getEolFromFile = (() => {
var _ref16 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path) {
if (!(yield exists(path))) {
return undefined;
}
const buffer = yield readFileBuffer(path);
for (let i = 0; i < buffer.length; ++i) {
if (buffer[i] === cr) {
return '\r\n';
}
if (buffer[i] === lf) {
return '\n';
}
}
return undefined;
});
return function getEolFromFile(_x30) {
return _ref16.apply(this, arguments);
};
})();
let writeFilePreservingEol = exports.writeFilePreservingEol = (() => {
var _ref17 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path, data) {
const eol = (yield getEolFromFile(path)) || os.EOL;
if (eol !== '\n') {
data = data.replace(/\n/g, eol);
}
yield (0, (_promise3 || _load_promise3()).promisify)(fs.writeFile)(path, data);
});
return function writeFilePreservingEol(_x31, _x32) {
return _ref17.apply(this, arguments);
};
})();
let hardlinksWork = exports.hardlinksWork = (() => {
var _ref18 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir) {
const filename = 'test-file' + Math.random();
const file = path.join(dir, filename);
const fileLink = path.join(dir, filename + '-link');
try {
yield writeFile(file, 'test');
yield link(file, fileLink);
} catch (err) {
return false;
} finally {
yield unlink(file);
yield unlink(fileLink);
}
return true;
});
return function hardlinksWork(_x33) {
return _ref18.apply(this, arguments);
};
})();
// not a strict polyfill for Node's fs.mkdtemp
let makeTempDir = exports.makeTempDir = (() => {
var _ref19 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (prefix) {
const dir = path.join(os.tmpdir(), `yarn-${prefix || ''}-${Date.now()}-${Math.random()}`);
yield unlink(dir);
yield mkdirp(dir);
return dir;
});
return function makeTempDir(_x34) {
return _ref19.apply(this, arguments);
};
})();
exports.copy = copy;
exports.readFile = readFile;
exports.readFileRaw = readFileRaw;
exports.normalizeOS = normalizeOS;
var _blockingQueue;
function _load_blockingQueue() {
return _blockingQueue = _interopRequireDefault(require('./blocking-queue.js'));
}
var _promise2;
function _load_promise2() {
return _promise2 = _interopRequireWildcard(require('./promise.js'));
}
var _promise3;
function _load_promise3() {
return _promise3 = require('./promise.js');
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('./map.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
const fs = require('fs');
const os = require('os');
const lockQueue = exports.lockQueue = new (_blockingQueue || _load_blockingQueue()).default('fs lock');
const readFileBuffer = exports.readFileBuffer = (0, (_promise3 || _load_promise3()).promisify)(fs.readFile);
const writeFile = exports.writeFile = (0, (_promise3 || _load_promise3()).promisify)(fs.writeFile);
const readlink = exports.readlink = (0, (_promise3 || _load_promise3()).promisify)(fs.readlink);
const realpath = exports.realpath = (0, (_promise3 || _load_promise3()).promisify)(fs.realpath);
const readdir = exports.readdir = (0, (_promise3 || _load_promise3()).promisify)(fs.readdir);
const rename = exports.rename = (0, (_promise3 || _load_promise3()).promisify)(fs.rename);
const access = exports.access = (0, (_promise3 || _load_promise3()).promisify)(fs.access);
const stat = exports.stat = (0, (_promise3 || _load_promise3()).promisify)(fs.stat);
const unlink = exports.unlink = (0, (_promise3 || _load_promise3()).promisify)(require('rimraf'));
const mkdirp = exports.mkdirp = (0, (_promise3 || _load_promise3()).promisify)(require('mkdirp'));
const exists = exports.exists = (0, (_promise3 || _load_promise3()).promisify)(fs.exists, true);
const lstat = exports.lstat = (0, (_promise3 || _load_promise3()).promisify)(fs.lstat);
const chmod = exports.chmod = (0, (_promise3 || _load_promise3()).promisify)(fs.chmod);
const link = exports.link = (0, (_promise3 || _load_promise3()).promisify)(fs.link);
const CONCURRENT_QUEUE_ITEMS = 4;
const fsSymlink = (0, (_promise3 || _load_promise3()).promisify)(fs.symlink);
const invariant = require('invariant');
const stripBOM = require('strip-bom');
const noop = () => {};
function copy(src, dest, reporter) {
return copyBulk([{ src: src, dest: dest }], reporter);
}
function _readFile(loc, encoding) {
return new (_promise || _load_promise()).default((resolve, reject) => {
fs.readFile(loc, encoding, function (err, content) {
if (err) {
reject(err);
} else {
resolve(content);
}
});
});
}
function readFile(loc) {
return _readFile(loc, 'utf8').then(normalizeOS);
}
function readFileRaw(loc) {
return _readFile(loc, 'binary');
}
function normalizeOS(body) {
return body.replace(/\r\n/g, '\n');
}
const cr = new Buffer('\r', 'utf8')[0];
const lf = new Buffer('\n', 'utf8')[0];
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 1 1 1 1 1 1 1 7 7 7 6 6 6 1 7 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _setPrototypeOf;
function _load_setPrototypeOf() {
return _setPrototypeOf = _interopRequireDefault(require('babel-runtime/core-js/object/set-prototype-of'));
}
exports.default = nullify;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function nullify() {
let obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
Iif (Array.isArray(obj)) {
for (const item of obj) {
nullify(item);
}
} else if (obj !== null && typeof obj === 'object' || typeof obj === 'function') {
(0, (_setPrototypeOf || _load_setPrototypeOf()).default)(obj, null);
// for..in can only be applied to 'object', not 'function'
Eif (typeof obj === 'object') {
for (const key in obj) {
nullify(obj[key]);
}
}
}
return obj;
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sortAlpha = sortAlpha;
exports.entries = entries;
exports.removePrefix = removePrefix;
exports.removeSuffix = removeSuffix;
exports.addSuffix = addSuffix;
exports.hyphenate = hyphenate;
exports.camelCase = camelCase;
const _camelCase = require('camelcase');
function sortAlpha(a, b) {
// sort alphabetically in a deterministic way
const shortLen = Math.min(a.length, b.length);
for (let i = 0; i < shortLen; i++) {
const aChar = a.charCodeAt(i);
const bChar = b.charCodeAt(i);
if (aChar !== bChar) {
return aChar - bChar;
}
}
return a.length - b.length;
}
function entries(obj) {
const entries = [];
if (obj) {
for (const key in obj) {
entries.push([key, obj[key]]);
}
}
return entries;
}
function removePrefix(pattern, prefix) {
if (pattern.startsWith(prefix)) {
pattern = pattern.slice(prefix.length);
}
return pattern;
}
function removeSuffix(pattern, suffix) {
if (pattern.endsWith(suffix)) {
return pattern.slice(0, -suffix.length);
}
return pattern;
}
function addSuffix(pattern, suffix) {
if (!pattern.endsWith(suffix)) {
return pattern + suffix;
}
return pattern;
}
function hyphenate(str) {
return str.replace(/[A-Z]/g, match => {
return '-' + match.charAt(0).toLowerCase();
});
}
function camelCase(str) {
if (/[A-Z]/.test(str)) {
return null;
} else {
return _camelCase(str);
}
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 1 1 1 1 1 1 1 1 1 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require("babel-runtime/core-js/promise"));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require("babel-runtime/core-js/map"));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const lockPromises = new (_map || _load_map()).default();
/**
* Acquires a mutex lock over the given key. If the lock can't be acquired, it waits until it's available.
* @param key Key to get the lock for.
* @return {Promise.<Function>} A Promise that resolves when the lock is acquired, with the function that
* must be called to release the lock.
*/
exports.default = key => {
let unlockNext;
const willLock = new (_promise || _load_promise()).default(resolve => unlockNext = resolve);
const lockPromise = lockPromises.get(key) || (_promise || _load_promise()).default.resolve();
const willUnlock = lockPromise.then(() => unlockNext);
lockPromises.set(key, lockPromise.then(() => willLock));
return willUnlock;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 1 1 1 1 1 1 1 1 1 1 2 2 2 2 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isOffline = isOffline;
const os = require('os');
const IGNORE_INTERFACES = ['lo0', 'awdl0', 'bridge0'];
const LOCAL_IPS = ['127.0.0.1', '::1'];
function isOffline() {
let interfaces;
try {
interfaces = os.networkInterfaces();
} catch (e) {
// As of October 2016, Windows Subsystem for Linux (WSL) does not support
// the os.networkInterfaces() call and throws instead. For this platform,
// assume we are online.
if (e.syscall === 'uv_interface_addresses') {
return false;
} else {
throw e;
}
}
for (const name in interfaces) {
Iif (IGNORE_INTERFACES.indexOf(name) >= 0) {
continue;
}
const addrs = interfaces[name];
for (const addr of addrs) {
if (LOCAL_IPS.indexOf(addr.address) < 0) {
// found a possible remote ip
return false;
}
}
}
return true;
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 1 1 1 1 1 1 1 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require("babel-runtime/helpers/slicedToArray"));
}
exports.default = parsePackageName;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const PKG_INPUT = /(^\S?[^\s@]+)(?:@(\S+))?$/;
function parsePackageName(input) {
var _PKG_INPUT$exec = PKG_INPUT.exec(input),
_PKG_INPUT$exec2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_PKG_INPUT$exec, 3);
const name = _PKG_INPUT$exec2[1],
version = _PKG_INPUT$exec2[2];
return { name: name, version: version };
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | 1 1 1 1 1 1 1 1 1 1 17 1 1 1 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require("babel-runtime/core-js/promise"));
}
exports.wait = wait;
exports.promisify = promisify;
exports.promisifyObject = promisifyObject;
exports.queue = queue;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function wait(delay) {
return new (_promise || _load_promise()).default(resolve => {
setTimeout(resolve, delay);
});
}
function promisify(fn, firstData) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return new (_promise || _load_promise()).default(function (resolve, reject) {
args.push(function (err) {
for (var _len2 = arguments.length, result = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
result[_key2 - 1] = arguments[_key2];
}
let res = result;
if (result.length <= 1) {
res = result[0];
}
if (firstData) {
res = err;
err = null;
}
if (err) {
reject(err);
} else {
resolve(res);
}
});
fn.apply(null, args);
});
};
}
function promisifyObject(obj) {
const promisedObj = {};
for (const key in obj) {
promisedObj[key] = promisify(obj[key]);
}
return promisedObj;
}
function queue(arr, promiseProducer) {
let concurrency = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Infinity;
concurrency = Math.min(concurrency, arr.length);
// clone
arr = arr.slice();
const results = [];
let total = arr.length;
if (!total) {
return (_promise || _load_promise()).default.resolve(results);
}
return new (_promise || _load_promise()).default((resolve, reject) => {
for (let i = 0; i < concurrency; i++) {
next();
}
function next() {
const item = arr.shift();
const promise = promiseProducer(item);
promise.then(function (result) {
results.push(result);
total--;
if (total === 0) {
resolve(results);
} else {
if (arr.length) {
next();
}
}
}, reject);
}
});
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _assign;
function _load_assign() {
return _assign = _interopRequireDefault(require('babel-runtime/core-js/object/assign'));
}
var _promise;
function _load_promise() {
return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _blockingQueue;
function _load_blockingQueue() {
return _blockingQueue = _interopRequireDefault(require('./blocking-queue.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _network;
function _load_network() {
return _network = _interopRequireWildcard(require('./network.js'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('../util/map.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const RequestCaptureHar = require('request-capture-har');
const invariant = require('invariant');
const url = require('url');
const fs = require('fs');
const successHosts = (0, (_map || _load_map()).default)();
const controlOffline = (_network || _load_network()).isOffline();
class RequestManager {
constructor(reporter) {
this.offlineNoRequests = false;
this._requestCaptureHar = null;
this._requestModule = null;
this.offlineQueue = [];
this.captureHar = false;
this.httpsProxy = null;
this.ca = null;
this.httpProxy = null;
this.strictSSL = true;
this.userAgent = '';
this.reporter = reporter;
this.running = 0;
this.queue = [];
this.cache = {};
this.max = (_constants || _load_constants()).NETWORK_CONCURRENCY;
}
setOptions(opts) {
if (opts.userAgent != null) {
this.userAgent = opts.userAgent;
}
if (opts.offline != null) {
this.offlineNoRequests = opts.offline;
}
if (opts.captureHar != null) {
this.captureHar = opts.captureHar;
}
if (opts.httpProxy != null) {
this.httpProxy = opts.httpProxy;
}
if (opts.httpsProxy != null) {
this.httpsProxy = opts.httpsProxy;
}
if (opts.strictSSL !== null && typeof opts.strictSSL !== 'undefined') {
this.strictSSL = opts.strictSSL;
}
if (opts.ca != null && opts.ca.length > 0) {
this.ca = opts.ca;
}
if (opts.networkConcurrency != null) {
this.max = opts.networkConcurrency;
}
if (opts.cafile != null && opts.cafile != '') {
// The CA bundle file can contain one or more certificates with comments/text between each PEM block.
// tls.connect wants an array of certificates without any comments/text, so we need to split the string
// and strip out any text in between the certificates
try {
const bundle = fs.readFileSync(opts.cafile).toString();
const hasPemPrefix = block => block.startsWith('-----BEGIN ');
// opts.cafile overrides opts.ca, this matches with npm behavior
this.ca = bundle.split(/(-----BEGIN .*\r?\n[^-]+\r?\n--.*)/).filter(hasPemPrefix);
} catch (err) {
this.reporter.error(`Could not open cafile: ${err.message}`);
}
}
if (opts.cert != null) {
this.cert = opts.cert;
}
if (opts.key != null) {
this.key = opts.key;
}
}
/**
* Lazy load `request` since it is exceptionally expensive to load and is
* often not needed at all.
*/
_getRequestModule() {
if (!this._requestModule) {
const request = require('request');
if (this.captureHar) {
this._requestCaptureHar = new RequestCaptureHar(request);
this._requestModule = this._requestCaptureHar.request.bind(this._requestCaptureHar);
} else {
this._requestModule = request;
}
}
return this._requestModule;
}
/**
* Queue up a request.
*/
request(params) {
if (this.offlineNoRequests) {
return (_promise || _load_promise()).default.reject(new (_errors || _load_errors()).MessageError(this.reporter.lang('cantRequestOffline')));
}
const cached = this.cache[params.url];
if (cached) {
return cached;
}
params.method = params.method || 'GET';
params.forever = true;
params.retryAttempts = 0;
params.strictSSL = this.strictSSL;
params.headers = (0, (_assign || _load_assign()).default)({
'User-Agent': this.userAgent
}, params.headers);
const promise = new (_promise || _load_promise()).default((resolve, reject) => {
this.queue.push({ params: params, resolve: resolve, reject: reject });
this.shiftQueue();
});
// we can't cache a request with a processor
if (!params.process) {
this.cache[params.url] = promise;
}
return promise;
}
/**
* Clear the request cache. This is important as we cache all HTTP requests so you'll
* want to do this as soon as you can.
*/
clearCache() {
this.cache = {};
if (this._requestCaptureHar != null) {
this._requestCaptureHar.clear();
}
}
/**
* Check if an error is possibly due to lost or poor network connectivity.
*/
isPossibleOfflineError(err) {
const code = err.code,
hostname = err.hostname;
if (!code) {
return false;
}
// network was previously online but now we're offline
const possibleOfflineChange = !controlOffline && !(_network || _load_network()).isOffline();
if (code === 'ENOTFOUND' && possibleOfflineChange) {
// can't resolve a domain
return true;
}
// used to be able to resolve this domain! something is wrong
if (code === 'ENOTFOUND' && hostname && successHosts[hostname]) {
// can't resolve this domain but we've successfully resolved it before
return true;
}
// network was previously offline and we can't resolve the domain
if (code === 'ENOTFOUND' && controlOffline) {
return true;
}
// connection was reset or dropped
if (code === 'ECONNRESET') {
return true;
}
return false;
}
/**
* Queue up request arguments to be retried. Start a network connectivity timer if there
* isn't already one.
*/
queueForOffline(opts) {
if (!this.offlineQueue.length) {
this.reporter.warn(this.reporter.lang('offlineRetrying'));
this.initOfflineRetry();
}
this.offlineQueue.push(opts);
}
/**
* Begin timers to retry failed requests when we possibly establish network connectivity
* again.
*/
initOfflineRetry() {
setTimeout(() => {
const queue = this.offlineQueue;
this.offlineQueue = [];
for (const opts of queue) {
this.execute(opts);
}
}, 3000);
}
/**
* Execute a request.
*/
execute(opts) {
const params = opts.params;
const reporter = this.reporter;
const buildNext = fn => data => {
fn(data);
this.running--;
this.shiftQueue();
};
const resolve = buildNext(opts.resolve);
const rejectNext = buildNext(opts.reject);
const reject = function reject(err) {
err.message = `${params.url}: ${err.message}`;
rejectNext(err);
};
//
let calledOnError = false;
const onError = err => {
if (calledOnError) {
return;
}
calledOnError = true;
const attempts = params.retryAttempts || 0;
if (attempts < 5 && this.isPossibleOfflineError(err)) {
params.retryAttempts = attempts + 1;
if (typeof params.cleanup === 'function') {
params.cleanup();
}
this.queueForOffline(opts);
} else {
reject(err);
}
};
if (!params.process) {
const parts = url.parse(params.url);
params.callback = (err, res, body) => {
if (err) {
onError(err);
return;
}
successHosts[parts.hostname] = true;
this.reporter.verbose(this.reporter.lang('verboseRequestFinish', params.url, res.statusCode));
if (body && typeof body.error === 'string') {
reject(new Error(body.error));
return;
}
if (res.statusCode === 403) {
const errMsg = body && body.message || reporter.lang('requestError', params.url, res.statusCode);
reject(new Error(errMsg));
} else {
if (res.statusCode === 400 || res.statusCode === 404 || res.statusCode === 401) {
body = false;
}
resolve(body);
}
};
}
if (params.buffer) {
params.encoding = null;
}
let proxy = this.httpProxy;
if (params.url.startsWith('https:')) {
proxy = this.httpsProxy || proxy;
}
if (proxy) {
params.proxy = proxy;
}
if (this.ca != null) {
params.ca = this.ca;
}
if (this.cert != null) {
params.cert = this.cert;
}
if (this.key != null) {
params.key = this.key;
}
const request = this._getRequestModule();
const req = request(params);
this.reporter.verbose(this.reporter.lang('verboseRequestStart', params.method, params.url));
req.on('error', onError);
const queue = params.queue;
if (queue) {
req.on('data', queue.stillActive.bind(queue));
}
if (params.process) {
params.process(req, resolve, reject);
}
}
/**
* Remove an item from the queue. Create it's request options and execute it.
*/
shiftQueue() {
if (this.running >= this.max || !this.queue.length) {
return;
}
const opts = this.queue.shift();
this.running++;
this.execute(opts);
}
saveHar(filename) {
if (!this.captureHar) {
throw new Error(this.reporter.lang('requestManagerNotSetupHAR'));
}
// No request may have occurred at all.
this._getRequestModule();
invariant(this._requestCaptureHar != null, 'request-capture-har not setup');
this._requestCaptureHar.saveHar(filename);
}
}
exports.default = RequestManager;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
const invariant = require('invariant');
const stream = require('stream');
const zlib = require('zlib');
function hasGzipHeader(chunk) {
return chunk[0] === 0x1F && chunk[1] === 0x8B && chunk[2] === 0x08;
}
class UnpackStream extends stream.Transform {
constructor(options) {
super(options);
this._srcStream = null;
this._readHeader = false;
this.once('pipe', src => {
this._srcStream = src;
});
}
_transform(chunk, encoding, callback) {
if (!this._readHeader) {
this._readHeader = true;
invariant(chunk instanceof Buffer, 'Chunk must be a buffer');
if (hasGzipHeader(chunk)) {
// Stop receiving data from the src stream, and pipe it instead to zlib,
// then pipe it's output through us.
const unzipStream = zlib.createUnzip();
unzipStream.on('error', err => this.emit('error', err));
const srcStream = this._srcStream;
invariant(srcStream, 'How? To get here a stream must have been piped!');
srcStream.pipe(unzipStream).pipe(this);
// Unpipe after another stream has been piped so it's always piping to
// something, thus avoiding pausing it.
srcStream.unpipe(this);
unzipStream.write(chunk);
this._srcStream = null;
callback();
return;
}
}
callback(null, chunk);
}
}
exports.UnpackStream = UnpackStream;
class ConcatStream extends stream.Transform {
constructor(done) {
super();
this._data = [];
this._done = done;
}
_transform(chunk, encoding, callback) {
invariant(chunk instanceof Buffer, 'Chunk must be a buffer');
invariant(this._data != null, 'Missing data array');
this._data.push(chunk);
this.push(chunk);
callback();
}
_flush(callback) {
invariant(this._data != null, 'Missing data array');
this._done(Buffer.concat(this._data));
this._data = null;
callback();
}
}
exports.ConcatStream = ConcatStream;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
const path = require('path');
var _require = require('../constants');
const ROOT_USER = _require.ROOT_USER;
const userHomeDir = process.platform === 'linux' && ROOT_USER ? path.resolve('/usr/local/share') : require('os').homedir();
exports.default = userHomeDir;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.explodeHashedUrl = explodeHashedUrl;
function explodeHashedUrl(url) {
const parts = url.split('#');
return {
url: parts[0],
hash: parts[1] || ''
};
}
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| fix.js | 14.13% | (26 / 184) | 2.42% | (5 / 207) | 12.5% | (2 / 16) | 14.37% | (25 / 174) | |
| infer-license.js | 38.1% | (8 / 21) | 0% | (0 / 12) | 0% | (0 / 4) | 40% | (8 / 20) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys;
function _load_keys() {
return _keys = _interopRequireDefault(require('babel-runtime/core-js/object/keys'));
}
var _toArray2;
function _load_toArray() {
return _toArray2 = _interopRequireDefault(require('babel-runtime/helpers/toArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _util;
function _load_util() {
return _util = require('./util.js');
}
var _index;
function _load_index() {
return _index = require('../../resolvers/index.js');
}
var _inferLicense;
function _load_inferLicense() {
return _inferLicense = _interopRequireDefault(require('./infer-license.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const semver = require('semver');
const path = require('path');
const url = require('url');
const LICENSE_RENAMES = {
'MIT/X11': 'MIT',
X11: 'MIT'
};
exports.default = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (info, moduleLoc, reporter, warn, looseSemver) {
const files = yield (_fs || _load_fs()).readdir(moduleLoc);
// clean info.version
if (typeof info.version === 'string' && !semver.valid(info.version)) {
info.version = semver.clean(info.version, looseSemver) || info.version;
}
// if name or version aren't set then set them to empty strings
info.name = info.name || '';
info.version = info.version || '';
// if the man field is a string then coerce it to an array
if (typeof info.man === 'string') {
info.man = [info.man];
}
// if the keywords field is a string then split it on any whitespace
if (typeof info.keywords === 'string') {
info.keywords = info.keywords.split(/\s+/g);
}
// if there's no contributors field but an authors field then expand it
if (!info.contributors && files.indexOf('AUTHORS') >= 0) {
const authorsFilepath = path.join(moduleLoc, 'AUTHORS');
const authorsFilestats = yield (_fs || _load_fs()).stat(authorsFilepath);
if (authorsFilestats.isFile()) {
let authors = yield (_fs || _load_fs()).readFile(authorsFilepath);
authors = authors.split(/\r?\n/g) // split on lines
.map(function (line) {
return line.replace(/^\s*#.*$/, '').trim();
}) // remove comments
.filter(function (line) {
return !!line;
}); // remove empty lines
info.contributors = authors;
}
}
// expand people fields to objects
if (typeof info.author === 'string' || typeof info.author === 'object') {
info.author = (0, (_util || _load_util()).normalizePerson)(info.author);
}
if (Array.isArray(info.contributors)) {
info.contributors = info.contributors.map((_util || _load_util()).normalizePerson);
}
if (Array.isArray(info.maintainers)) {
info.maintainers = info.maintainers.map((_util || _load_util()).normalizePerson);
}
// if there's no readme field then load the README file from the cwd
if (!info.readme) {
const readmeCandidates = files.filter(function (filename) {
const lower = filename.toLowerCase();
return lower === 'readme' || lower.indexOf('readme.') === 0;
}).sort(function (filename1, filename2) {
// favor files with extensions
return filename2.indexOf('.') - filename1.indexOf('.');
});
for (const readmeFilename of readmeCandidates) {
const readmeFilepath = path.join(moduleLoc, readmeFilename);
const readmeFileStats = yield (_fs || _load_fs()).stat(readmeFilepath);
if (readmeFileStats.isFile()) {
info.readmeFilename = readmeFilename;
info.readme = yield (_fs || _load_fs()).readFile(readmeFilepath);
break;
}
}
}
// if there's no description then take the first paragraph from the readme
if (!info.description && info.readme) {
const desc = (0, (_util || _load_util()).extractDescription)(info.readme);
if (desc) {
info.description = desc;
}
}
// support array of engine keys
if (Array.isArray(info.engines)) {
const engines = {};
for (const str of info.engines) {
if (typeof str === 'string') {
var _str$trim$split = str.trim().split(/ +/g),
_str$trim$split2 = (0, (_toArray2 || _load_toArray()).default)(_str$trim$split);
const name = _str$trim$split2[0],
patternParts = _str$trim$split2.slice(1);
engines[name] = patternParts.join(' ');
}
}
info.engines = engines;
}
// if the repository field is a string then assume it's a git repo and expand it
if (typeof info.repository === 'string') {
info.repository = {
type: 'git',
url: info.repository
};
}
const repo = info.repository;
// explode info.repository.url if it's a hosted git shorthand
if (repo && typeof repo === 'object' && typeof repo.url === 'string') {
repo.url = (0, (_index || _load_index()).hostedGitFragmentToGitUrl)(repo.url, reporter);
}
// allow bugs to be specified as a string, expand it to an object with a single url prop
if (typeof info.bugs === 'string') {
info.bugs = { url: info.bugs };
}
// normalize homepage url to http
if (typeof info.homepage === 'string') {
const parts = url.parse(info.homepage);
parts.protocol = parts.protocol || 'http:';
if (parts.pathname && !parts.hostname) {
parts.hostname = parts.pathname;
parts.pathname = '';
}
info.homepage = url.format(parts);
}
// if the `bin` field is as string then expand it to an object with a single property
// based on the original `bin` field and `name field`
// { name: "foo", bin: "cli.js" } -> { name: "foo", bin: { foo: "cli.js" } }
if (typeof info.name === 'string' && typeof info.bin === 'string') {
// Remove scoped package name for consistency with NPM's bin field fixing behaviour
const name = info.name.replace(/^@[^\/]+\//, '');
info.bin = { [name]: info.bin };
}
// bundleDependencies is an alias for bundledDependencies
if (info.bundledDependencies) {
info.bundleDependencies = info.bundledDependencies;
delete info.bundledDependencies;
}
let scripts;
// dummy script object to shove file inferred scripts onto
if (info.scripts && typeof info.scripts === 'object') {
scripts = info.scripts;
} else {
scripts = {};
}
// if there's a server.js file and no start script then set it to `node server.js`
if (!scripts.start && files.indexOf('server.js') >= 0) {
scripts.start = 'node server.js';
}
// if there's a binding.gyp file and no install script then set it to `node-gyp rebuild`
if (!scripts.install && files.indexOf('binding.gyp') >= 0) {
scripts.install = 'node-gyp rebuild';
}
// set scripts if we've polluted the empty object
if ((0, (_keys || _load_keys()).default)(scripts).length) {
info.scripts = scripts;
}
const dirs = info.directories;
if (dirs && typeof dirs === 'object') {
const binDir = dirs.bin;
if (!info.bin && binDir && typeof binDir === 'string') {
const bin = info.bin = {};
const fullBinDir = path.join(moduleLoc, binDir);
if (yield (_fs || _load_fs()).exists(fullBinDir)) {
for (const scriptName of yield (_fs || _load_fs()).readdir(fullBinDir)) {
if (scriptName[0] === '.') {
continue;
}
bin[scriptName] = path.join('.', binDir, scriptName);
}
} else {
warn(reporter.lang('manifestDirectoryNotFound', binDir, info.name));
}
}
const manDir = dirs.man;
if (!info.man && typeof manDir === 'string') {
const man = info.man = [];
const fullManDir = path.join(moduleLoc, manDir);
if (yield (_fs || _load_fs()).exists(fullManDir)) {
for (const filename of yield (_fs || _load_fs()).readdir(fullManDir)) {
if (/^(.*?)\.[0-9]$/.test(filename)) {
man.push(path.join('.', manDir, filename));
}
}
} else {
warn(reporter.lang('manifestDirectoryNotFound', manDir, info.name));
}
}
}
delete info.directories;
// normalize licenses field
const licenses = info.licenses;
if (Array.isArray(licenses) && !info.license) {
let licenseTypes = [];
for (let license of licenses) {
if (license && typeof license === 'object') {
license = license.type;
}
if (typeof license === 'string') {
licenseTypes.push(license);
}
}
licenseTypes = licenseTypes.filter((_util || _load_util()).isValidLicense);
if (licenseTypes.length === 1) {
info.license = licenseTypes[0];
} else if (licenseTypes.length) {
info.license = `(${licenseTypes.join(' OR ')})`;
}
}
const license = info.license;
// normalize license
if (license && typeof license === 'object') {
info.license = license.type;
}
// get license file
const licenseFile = files.find(function (filename) {
const lower = filename.toLowerCase();
return lower === 'license' || lower.startsWith('license.') || lower === 'unlicense' || lower.startsWith('unlicense.');
});
if (licenseFile) {
const licenseFilepath = path.join(moduleLoc, licenseFile);
const licenseFileStats = yield (_fs || _load_fs()).stat(licenseFilepath);
if (licenseFileStats.isFile()) {
const licenseContent = yield (_fs || _load_fs()).readFile(licenseFilepath);
const inferredLicense = (0, (_inferLicense || _load_inferLicense()).default)(licenseContent);
info.licenseText = licenseContent;
const license = info.license;
if (typeof license === 'string') {
if (inferredLicense && (0, (_util || _load_util()).isValidLicense)(inferredLicense) && !(0, (_util || _load_util()).isValidLicense)(license)) {
// some packages don't specify their license version but we can infer it based on their license file
const basicLicense = license.toLowerCase().replace(/(-like|\*)$/g, '');
const expandedLicense = inferredLicense.toLowerCase();
if (expandedLicense.startsWith(basicLicense)) {
// TODO consider doing something to notify the user
info.license = inferredLicense;
}
}
} else if (inferredLicense) {
// if there's no license then infer it based on the license file
info.license = inferredLicense;
} else {
// valid expression to refer to a license in a file
info.license = `SEE LICENSE IN ${licenseFile}`;
}
}
}
if (typeof info.license === 'string') {
// sometimes licenses are known by different names, reduce them
info.license = LICENSE_RENAMES[info.license] || info.license;
} else if (typeof info.readme === 'string') {
// the license might be at the bottom of the README
const inferredLicense = (0, (_inferLicense || _load_inferLicense()).default)(info.readme);
if (inferredLicense) {
info.license = inferredLicense;
}
}
});
return function (_x, _x2, _x3, _x4, _x5) {
return _ref.apply(this, arguments);
};
})();
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = inferLicense;
var _licenses;
function _load_licenses() {
return _licenses = _interopRequireDefault(require('./licenses.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function clean(str) {
return str.replace(/[^A-Za-z\s]/g, ' ').replace(/[\s]+/g, ' ').trim().toLowerCase();
}
const REGEXES = {
Unlicense: [/http:\/\/unlicense.org\//],
WTFPL: [/DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE/, /WTFPL\b/],
ISC: [/The ISC License/, /ISC\b/],
Apache: [/Apache License\b/],
MIT: [/MIT\b/],
BSD: [/BSD\b/]
};
function inferLicense(license) {
// check if we have any explicit licenses
const cleanLicense = clean(license);
for (const licenseName in (_licenses || _load_licenses()).default) {
const testLicense = (_licenses || _load_licenses()).default[licenseName];
if (cleanLicense.search(testLicense) >= 0) {
return licenseName;
}
}
// infer based on some keywords
for (const licenseName in REGEXES) {
for (const regex of REGEXES[licenseName]) {
if (license.search(regex) >= 0) {
return `${licenseName}*`;
}
}
}
return null;
}
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| api.js | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (0 / 0) | |
| config.js | 69.48% | (173 / 249) | 55.73% | (141 / 253) | 76.09% | (35 / 46) | 71.13% | (170 / 239) | |
| constants.js | 87.27% | (48 / 55) | 50% | (7 / 14) | 100% | (5 / 5) | 87.27% | (48 / 55) | |
| errors.js | 66.67% | (4 / 6) | 100% | (0 / 0) | 0% | (0 / 1) | 66.67% | (4 / 6) | |
| package-compatibility.js | 66.67% | (60 / 90) | 53.33% | (32 / 60) | 81.82% | (9 / 11) | 66.29% | (59 / 89) | |
| package-constraint-resolver.js | 87.5% | (7 / 8) | 50% | (1 / 2) | 100% | (2 / 2) | 87.5% | (7 / 8) | |
| package-fetcher.js | 79.01% | (64 / 81) | 56.25% | (27 / 48) | 94.44% | (17 / 18) | 85.92% | (61 / 71) | |
| package-hoister.js | 91.63% | (241 / 263) | 75.7% | (81 / 107) | 100% | (19 / 19) | 91.6% | (240 / 262) | |
| package-install-scripts.js | 77.3% | (143 / 185) | 61.9% | (52 / 84) | 92.31% | (24 / 26) | 80% | (140 / 175) | |
| package-linker.js | 77.88% | (169 / 217) | 48.63% | (71 / 146) | 89.74% | (35 / 39) | 80.19% | (166 / 207) | |
| package-reference.js | 73.58% | (39 / 53) | 35% | (7 / 20) | 53.85% | (7 / 13) | 75% | (39 / 52) | |
| package-request.js | 71.7% | (152 / 212) | 51.46% | (53 / 103) | 73.17% | (30 / 41) | 73.76% | (149 / 202) | |
| package-resolver.js | 59.2% | (119 / 201) | 52.63% | (30 / 57) | 67.74% | (21 / 31) | 59% | (118 / 200) |
| 1 2 | "use strict"; |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 5 1 1 1 1 1 1 1 1 527 527 178 349 747 201 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 428 428 428 25 403 403 403 403 403 403 5 398 398 403 4 4 2 2 174 174 348 348 348 348 348 174 174 173 173 173 7 166 340 340 173 173 173 180 180 180 180 180 180 187 187 187 176 176 176 173 173 173 3 3 3 3 3 176 176 176 176 176 176 176 176 176 352 352 352 352 352 352 352 352 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _executeLifecycleScript;
function _load_executeLifecycleScript() {
return _executeLifecycleScript = require('./util/execute-lifecycle-script.js');
}
var _index;
function _load_index() {
return _index = _interopRequireDefault(require('./util/normalize-manifest/index.js'));
}
var _errors;
function _load_errors() {
return _errors = require('./errors.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('./util/fs.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('./constants.js'));
}
var _packageConstraintResolver;
function _load_packageConstraintResolver() {
return _packageConstraintResolver = _interopRequireDefault(require('./package-constraint-resolver.js'));
}
var _requestManager;
function _load_requestManager() {
return _requestManager = _interopRequireDefault(require('./util/request-manager.js'));
}
var _index2;
function _load_index2() {
return _index2 = require('./registries/index.js');
}
var _index3;
function _load_index3() {
return _index3 = require('./reporters/index.js');
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('./util/map.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const detectIndent = require('detect-indent');
const invariant = require('invariant');
const path = require('path');
function sortObject(object) {
const sortedObject = {};
Object.keys(object).sort().forEach(item => {
sortedObject[item] = object[item];
});
return sortedObject;
}
class Config {
constructor(reporter) {
this.constraintResolver = new (_packageConstraintResolver || _load_packageConstraintResolver()).default(this, reporter);
this.requestManager = new (_requestManager || _load_requestManager()).default(reporter);
this.reporter = reporter;
this._init({});
}
//
//
//
//
//
//
//
//
//
//
//
//
// Whether we should ignore executing lifecycle scripts
//
//
//
//
/**
* Execute a promise produced by factory if it doesn't exist in our cache with
* the associated key.
*/
getCache(key, factory) {
const cached = this.cache[key];
if (cached) {
return cached;
}
return this.cache[key] = factory().catch(err => {
this.cache[key] = null;
throw err;
});
}
/**
* Get a config option from our yarn config.
*/
getOption(key) {
return this.registries.yarn.getOption(key);
}
/**
* Reduce a list of versions to a single one based on an input range.
*/
resolveConstraints(versions, range) {
return this.constraintResolver.reduce(versions, range);
}
/**
* Initialise config. Fetch registry options, find package roots.
*/
init() {
var _this = this;
let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this._init(opts);
yield (_fs || _load_fs()).mkdirp(_this.globalFolder);
yield (_fs || _load_fs()).mkdirp(_this.linkFolder);
_this.linkedModules = [];
const linkedModules = yield (_fs || _load_fs()).readdir(_this.linkFolder);
for (const dir of linkedModules) {
const linkedPath = path.join(_this.linkFolder, dir);
if (dir[0] === '@') {
// it's a scope, not a package
const scopedLinked = yield (_fs || _load_fs()).readdir(linkedPath);
_this.linkedModules.push(...scopedLinked.map(function (scopedDir) {
return path.join(dir, scopedDir);
}));
} else {
_this.linkedModules.push(dir);
}
}
for (const key of Object.keys((_index2 || _load_index2()).registries)) {
const Registry = (_index2 || _load_index2()).registries[key];
// instantiate registry
const registry = new Registry(_this.cwd, _this.registries, _this.requestManager);
yield registry.init();
_this.registries[key] = registry;
_this.registryFolders.push(registry.folder);
const rootModuleFolder = path.join(_this.cwd, registry.folder);
if (_this.rootModuleFolders.indexOf(rootModuleFolder) < 0) {
_this.rootModuleFolders.push(rootModuleFolder);
}
}
_this.networkConcurrency = opts.networkConcurrency || Number(_this.getOption('network-concurrency')) || (_constants || _load_constants()).NETWORK_CONCURRENCY;
_this.requestManager.setOptions({
userAgent: String(_this.getOption('user-agent')),
httpProxy: String(opts.httpProxy || _this.getOption('proxy') || ''),
httpsProxy: String(opts.httpsProxy || _this.getOption('https-proxy') || ''),
strictSSL: Boolean(_this.getOption('strict-ssl')),
ca: Array.prototype.concat(opts.ca || _this.getOption('ca') || []).map(String),
cafile: String(opts.cafile || _this.getOption('cafile') || ''),
cert: String(opts.cert || _this.getOption('cert') || ''),
key: String(opts.key || _this.getOption('key') || ''),
networkConcurrency: _this.networkConcurrency
});
_this._cacheRootFolder = String(opts.cacheFolder || _this.getOption('cache-folder') || (_constants || _load_constants()).MODULE_CACHE_DIRECTORY);
//init & create cacheFolder, tempFolder
_this.cacheFolder = path.join(_this._cacheRootFolder, 'v' + String((_constants || _load_constants()).CACHE_VERSION));
_this.tempFolder = opts.tempFolder || path.join(_this.cacheFolder, '.tmp');
yield (_fs || _load_fs()).mkdirp(_this.cacheFolder);
yield (_fs || _load_fs()).mkdirp(_this.tempFolder);
Iif (opts.production === 'false') {
_this.production = false;
} else Iif (_this.getOption('production') || process.env.NODE_ENV === 'production' && process.env.NPM_CONFIG_PRODUCTION !== 'false' && process.env.YARN_PRODUCTION !== 'false') {
_this.production = true;
} else {
_this.production = !!opts.production;
}
})();
}
_init(opts) {
this.rootModuleFolders = [];
this.registryFolders = [];
this.linkedModules = [];
this.registries = (0, (_map || _load_map()).default)();
this.cache = (0, (_map || _load_map()).default)();
this.cwd = opts.cwd || this.cwd || process.cwd();
this.looseSemver = opts.looseSemver == undefined ? true : opts.looseSemver;
this.commandName = opts.commandName || '';
this.preferOffline = !!opts.preferOffline;
this.modulesFolder = opts.modulesFolder;
this.globalFolder = opts.globalFolder || (_constants || _load_constants()).GLOBAL_MODULE_DIRECTORY;
this.linkFolder = opts.linkFolder || (_constants || _load_constants()).LINK_REGISTRY_DIRECTORY;
this.offline = !!opts.offline;
this.binLinks = !!opts.binLinks;
this.ignorePlatform = !!opts.ignorePlatform;
this.ignoreScripts = !!opts.ignoreScripts;
this.nonInteractive = !!opts.nonInteractive;
this.requestManager.setOptions({
offline: !!opts.offline && !opts.preferOffline,
captureHar: !!opts.captureHar
});
Iif (this.modulesFolder) {
this.rootModuleFolders.push(this.modulesFolder);
}
}
/**
* Generate an absolute module path.
*/
generateHardModulePath(pkg, ignoreLocation) {
invariant(this.cacheFolder, 'No package root');
invariant(pkg, 'Undefined package');
if (pkg.location && !ignoreLocation) {
return pkg.location;
}
let name = pkg.name;
let uid = pkg.uid;
Eif (pkg.registry) {
name = `${pkg.registry}-${name}`;
}
const hash = pkg.remote.hash;
if (pkg.version && pkg.version !== pkg.uid) {
uid = `${pkg.version}-${uid}`;
} else Eif (hash) {
uid += `-${hash}`;
}
return path.join(this.cacheFolder, `${name}-${uid}`);
}
/**
* Execute lifecycle scripts in the specified directory. Ignoring when the --ignore-scripts flag has been
* passed.
*/
executeLifecycleScript(commandName, cwd) {
Iif (this.ignoreScripts) {
return Promise.resolve();
} else {
return (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execFromManifest)(this, commandName, cwd || this.cwd);
}
}
/**
* Generate an absolute temporary filename location based on the input filename.
*/
getTemp(filename) {
invariant(this.tempFolder, 'No temp folder');
return path.join(this.tempFolder, filename);
}
/**
* Remote packages may be cached in a file system to be available for offline installation.
* Second time the same package needs to be installed it will be loaded from there.
* Given a package's filename, return a path in the offline mirror location.
*/
getOfflineMirrorPath(packageFilename) {
let mirrorPath;
for (const key of ['npm', 'yarn']) {
const registry = this.registries[key];
Iif (registry == null) {
continue;
}
const registryMirrorPath = registry.config['yarn-offline-mirror'];
Eif (registryMirrorPath == null) {
continue;
}
mirrorPath = registryMirrorPath;
}
Eif (mirrorPath == null) {
return null;
}
if (packageFilename == null) {
return mirrorPath;
}
return path.join(mirrorPath, path.basename(packageFilename));
}
/**
* Checker whether the folder input is a valid module folder. We output a yarn metadata
* file when we've successfully setup a folder so use this as a marker.
*/
isValidModuleDest(dest) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
Iif (!(yield (_fs || _load_fs()).exists(dest))) {
return false;
}
if (!(yield (_fs || _load_fs()).exists(path.join(dest, (_constants || _load_constants()).METADATA_FILENAME)))) {
return false;
}
return true;
})();
}
/**
* Read package metadata and normalized package info.
*/
readPackageMetadata(dir) {
var _this2 = this;
return this.getCache(`metadata-${dir}`, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const metadata = yield _this2.readJson(path.join(dir, (_constants || _load_constants()).METADATA_FILENAME));
const pkg = yield _this2.readManifest(dir, metadata.registry);
return {
package: pkg,
artifacts: metadata.artifacts || [],
hash: metadata.hash,
remote: metadata.remote,
registry: metadata.registry
};
}));
}
/**
* Read normalized package info according yarn-metadata.json
* throw an error if package.json was not found
*/
readManifest(dir, priorityRegistry) {
var _this3 = this;
let isRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const manifest = yield _this3.maybeReadManifest(dir, priorityRegistry, isRoot);
Eif (manifest) {
return manifest;
} else {
throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('couldntFindPackagejson', dir), 'ENOENT');
}
})();
}
/**
* try get the manifest file by looking
* 1. mainfest file in cache
* 2. manifest file in registry
*/
maybeReadManifest(dir, priorityRegistry) {
var _this4 = this;
let isRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return this.getCache(`manifest-${dir}`, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const metadataLoc = path.join(dir, (_constants || _load_constants()).METADATA_FILENAME);
Iif (!priorityRegistry && (yield (_fs || _load_fs()).exists(metadataLoc))) {
var _ref3 = yield _this4.readJson(metadataLoc);
priorityRegistry = _ref3.registry;
}
if (priorityRegistry) {
const file = yield _this4.tryManifest(dir, priorityRegistry, isRoot);
Eif (file) {
return file;
}
}
for (const registry of Object.keys((_index2 || _load_index2()).registries)) {
Iif (priorityRegistry === registry) {
continue;
}
const file = yield _this4.tryManifest(dir, registry, isRoot);
Eif (file) {
return file;
}
}
return null;
}));
}
/**
* Read the root manifest.
*/
readRootManifest() {
return this.readManifest(this.cwd, 'npm', true);
}
/**
* Try and find package info with the input directory and registry.
*/
tryManifest(dir, registry, isRoot) {
var _this5 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const filename = (_index2 || _load_index2()).registries[registry].filename;
const loc = path.join(dir, filename);
Eif (yield (_fs || _load_fs()).exists(loc)) {
const data = yield _this5.readJson(loc);
data._registry = registry;
data._loc = loc;
return (0, (_index || _load_index()).default)(data, dir, _this5, isRoot);
} else {
return null;
}
})();
}
/**
* Description
*/
getFolder(pkg) {
let registryName = pkg._registry;
Iif (!registryName) {
const ref = pkg._reference;
invariant(ref, 'expected reference');
registryName = ref.registry;
}
return this.registries[registryName].folder;
}
/**
* Get root manifests.
*/
getRootManifests() {
var _this6 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const manifests = {};
for (const registryName of (_index2 || _load_index2()).registryNames) {
const registry = (_index2 || _load_index2()).registries[registryName];
const jsonLoc = path.join(_this6.cwd, registry.filename);
let object = {};
let exists = false;
let indent;
if (yield (_fs || _load_fs()).exists(jsonLoc)) {
exists = true;
const info = yield _this6.readJson(jsonLoc, (_fs || _load_fs()).readJsonAndFile);
object = info.object;
indent = detectIndent(info.content).indent || undefined;
}
manifests[registryName] = { loc: jsonLoc, object, exists, indent };
}
return manifests;
})();
}
/**
* Save root manifests.
*/
saveRootManifests(manifests) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
for (const registryName of (_index2 || _load_index2()).registryNames) {
var _manifests$registryNa = manifests[registryName];
const loc = _manifests$registryNa.loc,
object = _manifests$registryNa.object,
exists = _manifests$registryNa.exists,
indent = _manifests$registryNa.indent;
if (!exists && !Object.keys(object).length) {
continue;
}
for (const field of (_constants || _load_constants()).DEPENDENCY_TYPES) {
if (object[field]) {
object[field] = sortObject(object[field]);
}
}
yield (_fs || _load_fs()).writeFilePreservingEol(loc, JSON.stringify(object, null, indent || (_constants || _load_constants()).DEFAULT_INDENT) + '\n');
}
})();
}
/**
* Call the passed factory (defaults to fs.readJson) and rethrow a pretty error message if it was the result
* of a syntax error.
*/
readJson(loc) {
var _this7 = this;
let factory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_fs || _load_fs()).readJson;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
try {
return yield factory(loc);
} catch (err) {
if (err instanceof SyntaxError) {
throw new (_errors || _load_errors()).MessageError(_this7.reporter.lang('jsonError', loc, err.message));
} else {
throw err;
}
}
})();
}
static create() {
let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let reporter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new (_index3 || _load_index3()).NoopReporter();
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const config = new Config(reporter);
yield config.init(opts);
return config;
})();
}
}
exports.default = Config;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getPathKey = getPathKey;
exports.isRootUser = isRootUser;
const path = require('path');
const userHome = require('./util/user-home-dir').default;
const DEPENDENCY_TYPES = exports.DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies'];
const YARN_REGISTRY = exports.YARN_REGISTRY = 'https://registry.yarnpkg.com';
const YARN_DOCS = exports.YARN_DOCS = 'https://yarnpkg.com/en/docs/cli/';
const YARN_INSTALLER_SH = exports.YARN_INSTALLER_SH = 'https://yarnpkg.com/install.sh';
const YARN_INSTALLER_MSI = exports.YARN_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi';
const SELF_UPDATE_VERSION_URL = exports.SELF_UPDATE_VERSION_URL = 'https://yarnpkg.com/latest-version';
const SELF_UPDATE_TARBALL_URL = exports.SELF_UPDATE_TARBALL_URL = 'https://yarnpkg.com/latest.tar.gz';
const SELF_UPDATE_DOWNLOAD_FOLDER = exports.SELF_UPDATE_DOWNLOAD_FOLDER = 'updates';
// cache version, bump whenever we make backwards incompatible changes
const CACHE_VERSION = exports.CACHE_VERSION = 1;
// lockfile version, bump whenever we make backwards incompatible changes
const LOCKFILE_VERSION = exports.LOCKFILE_VERSION = 1;
// max amount of network requests to perform concurrently
const NETWORK_CONCURRENCY = exports.NETWORK_CONCURRENCY = 8;
// max amount of child processes to execute concurrently
const CHILD_CONCURRENCY = exports.CHILD_CONCURRENCY = 5;
const REQUIRED_PACKAGE_KEYS = exports.REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid'];
function getDirectory(category) {
// use %LOCALAPPDATA%/Yarn on Windows
Iif (process.platform === 'win32' && process.env.LOCALAPPDATA) {
return path.join(process.env.LOCALAPPDATA, 'Yarn', category);
}
// otherwise use ~/.{category}/yarn
return path.join(userHome, `.${category}`, 'yarn');
}
function getCacheDirectory() {
Iif (process.platform === 'darwin') {
return path.join(userHome, 'Library', 'Caches', 'Yarn');
}
return getDirectory('cache');
}
const MODULE_CACHE_DIRECTORY = exports.MODULE_CACHE_DIRECTORY = getCacheDirectory();
const CONFIG_DIRECTORY = exports.CONFIG_DIRECTORY = getDirectory('config');
const LINK_REGISTRY_DIRECTORY = exports.LINK_REGISTRY_DIRECTORY = path.join(CONFIG_DIRECTORY, 'link');
const GLOBAL_MODULE_DIRECTORY = exports.GLOBAL_MODULE_DIRECTORY = path.join(CONFIG_DIRECTORY, 'global');
const CACHE_FILENAME = exports.CACHE_FILENAME = path.join(MODULE_CACHE_DIRECTORY, '.roadrunner.json');
const INTEGRITY_FILENAME = exports.INTEGRITY_FILENAME = '.yarn-integrity';
const LOCKFILE_FILENAME = exports.LOCKFILE_FILENAME = 'yarn.lock';
const METADATA_FILENAME = exports.METADATA_FILENAME = '.yarn-metadata.json';
const TARBALL_FILENAME = exports.TARBALL_FILENAME = '.yarn-tarball.tgz';
const CLEAN_FILENAME = exports.CLEAN_FILENAME = '.yarnclean';
const DEFAULT_INDENT = exports.DEFAULT_INDENT = ' ';
const SINGLE_INSTANCE_PORT = exports.SINGLE_INSTANCE_PORT = 31997;
const SINGLE_INSTANCE_FILENAME = exports.SINGLE_INSTANCE_FILENAME = '.yarn-single-instance';
const ENV_PATH_KEY = exports.ENV_PATH_KEY = getPathKey(process.platform, process.env);
function getPathKey(platform, env) {
let pathKey = 'PATH';
// windows calls its path "Path" usually, but this is not guaranteed.
Iif (platform === 'win32') {
pathKey = 'Path';
for (const key in env) {
if (key.toLowerCase() === 'path') {
pathKey = key;
}
}
}
return pathKey;
}
function getUid() {
Eif (process.platform !== 'win32' && process.getuid) {
return process.getuid();
}
return null;
}
const ROOT_USER = exports.ROOT_USER = isRootUser(getUid());
function isRootUser(uid) {
return uid === 0;
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 1 1 1 1 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
class MessageError extends Error {
constructor(msg, code) {
super(msg);
this.code = code;
}
}
exports.MessageError = MessageError;
class SecurityError extends MessageError {}
exports.SecurityError = SecurityError;
class SpawnError extends MessageError {}
exports.SpawnError = SpawnError;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 4 4 4 2 1 1 1 82 82 82 82 82 1 1 1 1 2 173 173 173 173 173 173 173 173 173 173 81 83 83 83 1 83 82 1 173 1 1 173 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.testEngine = testEngine;
var _errors;
function _load_errors() {
return _errors = require('./errors.js');
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('./util/map.js'));
}
var _misc;
function _load_misc() {
return _misc = require('./util/misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const semver = require('semver');
const VERSIONS = Object.assign({}, process.versions, {
yarn: require('../package.json').version
});
function isValid(items, actual) {
let isNotWhitelist = true;
let isBlacklist = false;
for (const item of items) {
// blacklist
Iif (item[0] === '!') {
isBlacklist = true;
if (actual === item.slice(1)) {
return false;
}
// whitelist
} else {
isNotWhitelist = false;
if (item === actual) {
return true;
}
}
}
// npm allows blacklists and whitelists to be mixed. Blacklists with
// whitelisted items should be treated as whitelists.
return isBlacklist && isNotWhitelist;
}
const aliases = (0, (_map || _load_map()).default)({
iojs: 'node' });
const ignore = ['npm', // we'll never satisfy this for obvious reasons
'teleport', // a module bundler used by some modules
'rhino'];
function testEngine(name, range, versions, looseSemver) {
const actual = versions[name];
Iif (!actual) {
return false;
}
Iif (!semver.valid(actual, looseSemver)) {
return false;
}
Eif (semver.satisfies(actual, range, looseSemver)) {
return true;
}
if (name === 'node' && semver.gt(actual, '1.0.0', looseSemver)) {
// WARNING: this is a massive hack and is super gross but necessary for compatibility
// some modules have the `engines.node` field set to a caret version below semver major v1
// eg. ^0.12.0. this is problematic as we enforce engines checks and node is now on version >=1
// to allow this pattern we transform the node version to fake ones in the minor range 10-13
const major = semver.major(actual, looseSemver);
const fakes = [`0.10.${major}`, `0.11.${major}`, `0.12.${major}`, `0.13.${major}`];
for (const actualFake of fakes) {
if (semver.satisfies(actualFake, range, looseSemver)) {
return true;
}
}
}
// incompatible version
return false;
}
class PackageCompatibility {
constructor(config, resolver, ignoreEngines) {
this.reporter = config.reporter;
this.resolver = resolver;
this.config = config;
this.ignoreEngines = ignoreEngines;
}
static isValidArch(archs) {
return isValid(archs, process.arch);
}
static isValidPlatform(platforms) {
return isValid(platforms, process.platform);
}
check(info) {
let didIgnore = false;
let didError = false;
const reporter = this.reporter;
const human = `${info.name}@${info.version}`;
const pushError = msg => {
const ref = info._reference;
invariant(ref, 'expected package reference');
if (ref.optional) {
ref.ignore = true;
reporter.warn(`${human}: ${msg}`);
if (!didIgnore) {
reporter.info(reporter.lang('optionalCompatibilityExcluded', human));
didIgnore = true;
}
} else {
reporter.error(`${human}: ${msg}`);
didError = true;
}
};
const invalidPlatform = !this.config.ignorePlatform && Array.isArray(info.os) && info.os.length > 0 && !PackageCompatibility.isValidPlatform(info.os);
Iif (invalidPlatform) {
pushError(this.reporter.lang('incompatibleOS', process.platform));
}
const invalidCpu = !this.config.ignorePlatform && Array.isArray(info.cpu) && info.cpu.length > 0 && !PackageCompatibility.isValidArch(info.cpu);
Iif (invalidCpu) {
pushError(this.reporter.lang('incompatibleCPU', process.arch));
}
if (!this.ignoreEngines && typeof info.engines === 'object') {
for (const entry of (0, (_misc || _load_misc()).entries)(info.engines)) {
let name = entry[0];
const range = entry[1];
if (aliases[name]) {
name = aliases[name];
}
if (VERSIONS[name]) {
Iif (!testEngine(name, range, VERSIONS, this.config.looseSemver)) {
pushError(this.reporter.lang('incompatibleEngine', name, range));
}
} else Iif (ignore.indexOf(name) < 0) {
this.reporter.warn(`${human}: ${this.reporter.lang('invalidEngine', name)}`);
}
}
}
Iif (didError) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('foundIncompatible'));
}
}
init() {
const infos = this.resolver.getManifests();
for (const info of infos) {
this.check(info);
}
return Promise.resolve();
}
}
exports.default = PackageCompatibility;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 1 1 1 1 201 201 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
const semver = require('semver');
// This isn't really a "proper" constraint resolver. We just return the highest semver
// version in the versions passed that satisfies the input range. This vastly reduces
// the complexity and is very efficient for package resolution.
class PackageConstraintResolver {
constructor(config, reporter) {
this.reporter = reporter;
this.config = config;
}
reduce(versions, range) {
Iif (range === 'latest') {
// Usually versions are already ordered and the last one is the latest
return Promise.resolve(versions[versions.length - 1]);
} else {
return Promise.resolve(semver.maxSatisfying(versions, range, this.config.looseSemver));
}
}
}
exports.default = PackageConstraintResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 166 166 166 166 166 173 173 173 173 173 173 173 173 166 7 7 7 173 173 173 173 1 1 1 1 1 1 173 173 173 173 173 171 173 173 173 173 173 1 173 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _errors;
function _load_errors() {
return _errors = require('./errors.js');
}
var _index;
function _load_index() {
return _index = _interopRequireWildcard(require('./fetchers/index.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('./util/fs.js'));
}
var _promise;
function _load_promise() {
return _promise = _interopRequireWildcard(require('./util/promise.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class PackageFetcher {
constructor(config, resolver) {
this.reporter = config.reporter;
this.resolver = resolver;
this.config = config;
}
fetchCache(dest, fetcher) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
var _ref = yield _this.config.readPackageMetadata(dest);
const hash = _ref.hash,
pkg = _ref.package;
return {
package: pkg,
resolved: yield fetcher.getResolvedFromCached(hash),
hash,
dest,
cached: true
};
})();
}
fetch(ref) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const dest = _this2.config.generateHardModulePath(ref);
const remote = ref.remote;
const Fetcher = (_index || _load_index())[remote.type];
Iif (!Fetcher) {
throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('unknownFetcherFor', remote.type));
}
const fetcher = new Fetcher(dest, remote, _this2.config);
if (yield _this2.config.isValidModuleDest(dest)) {
return _this2.fetchCache(dest, fetcher);
}
// remove as the module may be invalid
yield (_fs || _load_fs()).unlink(dest);
try {
return yield fetcher.fetch();
} catch (err) {
try {
yield (_fs || _load_fs()).unlink(dest);
} catch (err2) {
// what do?
}
throw err;
}
})();
}
maybeFetch(ref) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
try {
return yield _this3.fetch(ref);
} catch (err) {
if (ref.optional) {
_this3.reporter.error(err.message);
return null;
} else {
throw err;
}
}
})();
}
init() {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const pkgs = _this4.resolver.getPackageReferences();
const tick = _this4.reporter.progress(pkgs.length);
yield (_promise || _load_promise()).queue(pkgs, (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (ref) {
const res = yield _this4.maybeFetch(ref);
let newPkg;
Eif (res) {
newPkg = res.package;
// update with new remote
// but only if there was a hash previously as the tarball fetcher does not provide a hash.
if (ref.remote.hash) {
ref.remote.hash = res.hash;
}
Iif (res.resolved) {
ref.remote.resolved = res.resolved;
}
}
Eif (newPkg) {
// update with fresh manifest
yield _this4.resolver.updateManifest(ref, newPkg);
}
Eif (tick) {
tick(ref.name);
}
});
return function (_x) {
return _ref2.apply(this, arguments);
};
})(), _this4.config.networkConcurrency);
})();
}
}
exports.default = PackageFetcher;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | 1 1 1 1 1 1 1 1 1 1 1 1 229 229 229 229 229 229 229 229 229 229 967 1 1 1 1 1 1 452 452 452 452 1919 1 1 3 1 7 7 1 1 6 6 1543 1543 1543 1543 1543 6 6 304 304 304 304 304 224 6 224 309 309 309 309 309 309 309 304 80 224 224 229 229 229 229 229 229 229 304 229 1 1 173 173 1 173 173 173 173 224 224 224 224 224 224 447 447 447 447 224 224 224 224 224 224 226 226 226 226 226 59 56 56 56 3 3 167 167 168 169 169 169 169 169 169 168 168 171 171 171 171 171 3 168 168 3 168 3 3 3 3 3 3 168 224 224 224 224 224 224 224 56 56 56 168 2 2 2 166 166 222 222 223 223 223 223 168 168 168 168 168 2 166 166 1 1 1 426 426 426 426 426 426 426 426 423 1 1 3 3 1 3 1 170 170 170 167 3 3 3 3 3 6 6 6 6 4 4 3 3 3 2 1 1 173 173 173 173 173 173 176 176 176 176 176 173 173 173 173 173 1 1 173 173 173 173 173 173 173 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.HoistManifest = undefined;
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _misc;
function _load_misc() {
return _misc = require('./util/misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const path = require('path');
let historyCounter = 0;
class HoistManifest {
constructor(key, parts, pkg, loc, isIgnored, inheritIsIgnored) {
this.isIgnored = isIgnored;
this.inheritIsIgnored = inheritIsIgnored;
this.loc = loc;
this.pkg = pkg;
this.key = key;
this.parts = parts;
this.originalKey = key;
this.previousKeys = [];
this.history = [];
this.addHistory(`Start position = ${key}`);
}
addHistory(msg) {
this.history.push(`${++historyCounter}: ${msg}`);
}
}
exports.HoistManifest = HoistManifest;
class PackageHoister {
constructor(config, resolver) {
this.resolver = resolver;
this.config = config;
this.taintedKeys = new Map();
this.levelQueue = [];
this.tree = new Map();
}
/**
* Taint this key and prevent any modules from being hoisted to it.
*/
taintKey(key, info) {
const existingTaint = this.taintedKeys.get(key);
Iif (existingTaint && existingTaint.loc !== info.loc) {
return false;
} else {
this.taintedKeys.set(key, info);
return true;
}
}
/**
* Implode an array of ancestry parts into a key.
*/
implodeKey(parts) {
return parts.join('#');
}
/**
* Seed the hoister with patterns taken from the included resolver.
*/
seed(patterns) {
this.prepass(patterns);
for (const pattern of this.resolver.dedupePatterns(patterns)) {
this._seed(pattern);
}
while (true) {
let queue = this.levelQueue;
if (!queue.length) {
this._propagateNonIgnored();
return;
}
this.levelQueue = [];
// sort queue to get determinism between runs
queue = queue.sort((_ref, _ref2) => {
var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 1);
let aPattern = _ref4[0];
var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 1);
let bPattern = _ref3[0];
return (0, (_misc || _load_misc()).sortAlpha)(aPattern, bPattern);
});
//
const infos = [];
for (const _ref5 of queue) {
var _ref6 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref5, 2);
const pattern = _ref6[0];
const parents = _ref6[1];
const info = this._seed(pattern, parents);
if (info) {
infos.push(info);
}
}
//
for (const info of infos) {
this.hoist(info);
}
}
}
/**
* Seed the hoister with a specific pattern.
*/
_seed(pattern, parent) {
//
const pkg = this.resolver.getStrictResolvedPattern(pattern);
const ref = pkg._reference;
invariant(ref, 'expected reference');
//
let parentParts = [];
let isIgnored = ref.ignore;
let inheritIsIgnored = false;
if (parent) {
if (!this.tree.get(parent.key)) {
return null;
}
// non ignored dependencies inherit parent's ignored status
// parent may transition from ignored to non ignored when hoisted if it is used in another non ignored branch
Iif (!isIgnored && parent.isIgnored) {
isIgnored = parent.isIgnored;
inheritIsIgnored = true;
}
parentParts = parent.parts;
}
//
const loc = this.config.generateHardModulePath(ref);
const parts = parentParts.concat(pkg.name);
const key = this.implodeKey(parts);
const info = new HoistManifest(key, parts, pkg, loc, isIgnored, inheritIsIgnored);
//
this.tree.set(key, info);
this.taintKey(key, info);
//
for (const depPattern of ref.dependencies) {
this.levelQueue.push([depPattern, info]);
}
return info;
}
/**
* Propagate inherited ignore statuses from non-ignored to ignored packages
*/
_propagateNonIgnored() {
//
const toVisit = [];
// enumerate all non-ignored packages
for (const entry of this.tree.entries()) {
Eif (!entry[1].isIgnored) {
toVisit.push(entry[1]);
}
}
// visit them
while (toVisit.length) {
const info = toVisit.shift();
const ref = info.pkg._reference;
invariant(ref, 'expected reference');
for (const depPattern of ref.dependencies) {
const depinfo = this._lookupDependency(info, depPattern);
Iif (depinfo && depinfo.isIgnored && depinfo.inheritIsIgnored) {
depinfo.isIgnored = false;
info.addHistory(`Mark as non-ignored because of usage by ${info.key}`);
toVisit.push(depinfo);
}
}
}
}
/**
* Looks up the package a dependency resolves to
*/
_lookupDependency(info, depPattern) {
//
const pkg = this.resolver.getStrictResolvedPattern(depPattern);
const ref = pkg._reference;
invariant(ref, 'expected reference');
//
for (let i = info.parts.length; i >= 0; i--) {
const checkParts = info.parts.slice(0, i).concat(pkg.name);
const checkKey = this.implodeKey(checkParts);
const existing = this.tree.get(checkKey);
if (existing) {
return existing;
}
}
return null;
}
/**
* Find the highest position we can hoist this module to.
*/
getNewParts(key, info, parts) {
let stepUp = false;
const fullKey = this.implodeKey(parts);
const stack = []; // stack of removed parts
const name = parts.pop();
//
for (let i = parts.length - 1; i >= 0; i--) {
const checkParts = parts.slice(0, i).concat(name);
const checkKey = this.implodeKey(checkParts);
info.addHistory(`Looked at ${checkKey} for a match`);
const existing = this.tree.get(checkKey);
if (existing) {
if (existing.loc === info.loc) {
// switch to non ignored if earlier deduped version was ignored
Iif (existing.isIgnored && !info.isIgnored) {
existing.isIgnored = info.isIgnored;
}
existing.addHistory(`Deduped ${fullKey} to this item`);
return { parts: checkParts, duplicate: true };
} else {
// everything above will be shadowed and this is a conflict
info.addHistory(`Found a collision at ${checkKey}`);
break;
}
}
const existingTaint = this.taintedKeys.get(checkKey);
Iif (existingTaint && existingTaint.loc !== info.loc) {
info.addHistory(`Broken by ${checkKey}`);
break;
}
}
// remove redundant parts that wont collide
while (parts.length) {
const checkParts = parts.concat(name);
const checkKey = this.implodeKey(checkParts);
//
const existing = this.tree.get(checkKey);
Iif (existing) {
stepUp = true;
break;
}
// check if we're trying to hoist ourselves to a previously unflattened module key,
// this will result in a conflict and we'll need to move ourselves up
Iif (key !== checkKey && this.taintedKeys.has(checkKey)) {
stepUp = true;
break;
}
//
stack.push(parts.pop());
}
//
parts.push(name);
//
const isValidPosition = parts => {
const key = this.implodeKey(parts);
const existing = this.tree.get(key);
Iif (existing && existing.loc === info.loc) {
return true;
}
// ensure there's no taint or the taint is us
const existingTaint = this.taintedKeys.get(key);
if (existingTaint && existingTaint.loc !== info.loc) {
return false;
}
return true;
};
// we need to special case when we attempt to hoist to the top level as the `existing` logic
// wont be hit in the above `while` loop and we could conflict
if (!isValidPosition(parts)) {
stepUp = true;
}
// sometimes we need to step up to a parent module to install ourselves
while (stepUp && stack.length) {
info.addHistory(`Stepping up from ${this.implodeKey(parts)}`);
parts.pop(); // remove `name`
parts.push(stack.pop(), name);
Eif (isValidPosition(parts)) {
info.addHistory(`Found valid position ${this.implodeKey(parts)}`);
stepUp = false;
}
}
return { parts, duplicate: false };
}
/**
* Hoist all seeded patterns to their highest positions.
*/
hoist(info) {
const key = info.key,
rawParts = info.parts;
// remove this item from the `tree` map so we can ignore it
this.tree.delete(key);
var _getNewParts = this.getNewParts(key, info, rawParts.slice());
const parts = _getNewParts.parts,
duplicate = _getNewParts.duplicate;
const newKey = this.implodeKey(parts);
const oldKey = key;
if (duplicate) {
info.addHistory(`Satisfied from above by ${newKey}`);
this.declareRename(info, rawParts, parts);
return;
}
// update to the new key
if (oldKey === newKey) {
info.addHistory("Didn't hoist - conflicts above");
this.setKey(info, oldKey, parts);
return;
}
//
this.declareRename(info, rawParts, parts);
this.setKey(info, newKey, parts);
}
/**
* Declare that a module has been hoisted and update our internal references.
*/
declareRename(info, oldParts, newParts) {
// go down the tree from our new position reserving our name
this.taintParents(info, oldParts.slice(0, -1), newParts.length - 1);
}
/**
* Crawl upwards through a list of ancestry parts and taint a package name.
*/
taintParents(info, processParts, start) {
for (let i = start; i < processParts.length; i++) {
const parts = processParts.slice(0, i).concat(info.pkg.name);
const key = this.implodeKey(parts);
Eif (this.taintKey(key, info)) {
info.addHistory(`Tainted ${key} to prevent collisions`);
}
}
}
/**
* Update the key of a module and update our references.
*/
setKey(info, newKey, parts) {
const oldKey = info.key;
info.key = newKey;
info.parts = parts;
this.tree.set(newKey, info);
if (oldKey === newKey) {
return;
}
info.previousKeys.push(newKey);
info.addHistory(`New position = ${newKey}`);
}
/**
* Perform a prepass and if there's multiple versions of the same package, hoist the one with
* the most dependents to the top.
*/
prepass(patterns) {
patterns = this.resolver.dedupePatterns(patterns).sort();
const occurences = {};
// add an occuring package to the above data structure
const add = (pattern, ancestry) => {
const pkg = this.resolver.getStrictResolvedPattern(pattern);
Iif (ancestry.indexOf(pkg) >= 0) {
// prevent recursive dependencies
return;
}
const ref = pkg._reference;
invariant(ref, 'expected reference');
const versions = occurences[pkg.name] = occurences[pkg.name] || {};
const version = versions[pkg.version] = versions[pkg.version] || { occurences: new Set(), pattern };
version.occurences.add(ancestry[ancestry.length - 1]);
for (const depPattern of ref.dependencies) {
add(depPattern, ancestry.concat(pkg));
}
};
// get a list of root package names since we can't hoist other dependencies to these spots!
const rootPackageNames = new Set();
for (const pattern of patterns) {
const pkg = this.resolver.getStrictResolvedPattern(pattern);
rootPackageNames.add(pkg.name);
}
// seed occurences
for (const pattern of patterns) {
add(pattern, []);
}
for (const packageName of Object.keys(occurences).sort()) {
const versionOccurences = occurences[packageName];
const versions = Object.keys(versionOccurences);
if (versions.length === 1) {
// only one package type so we'll hoist this to the top anyway
continue;
}
Iif (this.tree.get(packageName)) {
// a transitive dependency of a previously hoisted dependency exists
continue;
}
Iif (rootPackageNames.has(packageName)) {
// can't replace top level packages
continue;
}
let mostOccurenceCount;
let mostOccurencePattern;
for (const version of Object.keys(versionOccurences).sort()) {
var _versionOccurences$ve = versionOccurences[version];
const occurences = _versionOccurences$ve.occurences,
pattern = _versionOccurences$ve.pattern;
const occurenceCount = occurences.size;
if (!mostOccurenceCount || occurenceCount > mostOccurenceCount) {
mostOccurenceCount = occurenceCount;
mostOccurencePattern = pattern;
}
}
invariant(mostOccurencePattern, 'expected most occuring pattern');
invariant(mostOccurenceCount, 'expected most occuring count');
// only hoist this module if it occured more than once
if (mostOccurenceCount > 1) {
this._seed(mostOccurencePattern);
}
}
}
/**
* Produce a flattened list of module locations and manifests.
*/
init() {
const flatTree = [];
//
for (const _ref7 of this.tree.entries()) {
var _ref8 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref7, 2);
const key = _ref8[0];
const info = _ref8[1];
// decompress the location and push it to the flat tree. this path could be made
const parts = [];
const keyParts = key.split('#');
for (let i = 0; i < keyParts.length; i++) {
const key = keyParts.slice(0, i + 1).join('#');
const hoisted = this.tree.get(key);
invariant(hoisted, 'expected hoisted manifest');
parts.push(this.config.getFolder(hoisted.pkg));
parts.push(keyParts[i]);
}
Iif (this.config.modulesFolder) {
// remove the first part which will be the folder name and replace it with a
// hardcoded modules folder
parts.shift();
const modulesFolder = this.config.modulesFolder == null ? '' : this.config.modulesFolder;
parts.unshift(modulesFolder);
} else {
// first part will be the registry-specific module folder
const cwd = this.config.cwd == null ? '' : this.config.cwd;
parts.unshift(cwd);
}
const loc = path.join(...parts);
flatTree.push([loc, info]);
}
// remove ignored modules from the tree
const visibleFlatTree = [];
for (const _ref9 of flatTree) {
var _ref10 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref9, 2);
const loc = _ref10[0];
const info = _ref10[1];
const ref = info.pkg._reference;
invariant(ref, 'expected reference');
Iif (info.isIgnored) {
info.addHistory('Deleted as this module was ignored');
} else {
visibleFlatTree.push([loc, info]);
}
}
return visibleFlatTree;
}
}
exports.default = PackageHoister;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 4 1 1 1 1 1 1 1 1 521 521 476 476 1428 1428 8 476 45 4 4 4 4 4 133 4 2 2 2 2 2 103 103 103 103 73 2 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 519 519 513 6 6 6 6 6 2 2 2 2 2 173 173 173 173 173 173 224 224 173 173 5 5 5 178 5 173 173 173 173 2 173 173 173 1 1 1 1 1 1 1 1 173 2 2 2 2 2 173 1 1 1 1 5 1 1 173 2 2 2 2 2 2 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _executeLifecycleScript;
function _load_executeLifecycleScript() {
return _executeLifecycleScript = _interopRequireDefault(require('./util/execute-lifecycle-script.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('./util/fs.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('./constants.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const path = require('path');
const INSTALL_STAGES = ['preinstall', 'install', 'postinstall'];
class PackageInstallScripts {
constructor(config, resolver, force) {
this.installed = 0;
this.resolver = resolver;
this.reporter = config.reporter;
this.config = config;
this.force = force;
}
getInstallCommands(pkg) {
const scripts = pkg.scripts;
if (scripts) {
const cmds = [];
for (const stage of INSTALL_STAGES) {
const cmd = scripts[stage];
if (cmd) {
cmds.push([stage, cmd]);
}
}
return cmds;
} else {
return [];
}
}
walk(loc) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const files = yield (_fs || _load_fs()).walk(loc, null, new Set(_this.config.registryFolders));
const mtimes = new Map();
for (const file of files) {
mtimes.set(file.relative, file.mtime);
}
return mtimes;
})();
}
saveBuildArtifacts(loc, pkg, beforeFiles, spinner) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const afterFiles = yield _this2.walk(loc);
// work out what files have been created/modified
const buildArtifacts = [];
for (const _ref of afterFiles) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const file = _ref2[0];
const mtime = _ref2[1];
if (!beforeFiles.has(file) || beforeFiles.get(file) !== mtime) {
buildArtifacts.push(file);
}
}
if (!buildArtifacts.length) {
// nothing else to do here since we have no build artifacts
return;
}
// if the process is killed while copying over build artifacts then we'll leave
// the cache in a bad state. remove the metadata file and add it back once we've
// done our copies to ensure cache integrity.
const cachedLoc = _this2.config.generateHardModulePath(pkg._reference, true);
const metadata = yield _this2.config.readPackageMetadata(cachedLoc);
metadata.artifacts = buildArtifacts;
const metadataLoc = path.join(cachedLoc, (_constants || _load_constants()).METADATA_FILENAME);
yield (_fs || _load_fs()).writeFile(metadataLoc, JSON.stringify((0, (_extends2 || _load_extends()).default)({}, metadata, {
// config.readPackageMetadata also returns the package manifest but that's not in the original
// metadata json
package: undefined
}), null, ' '));
})();
}
install(cmds, pkg, spinner) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const ref = pkg._reference;
invariant(ref, 'expected reference');
const loc = _this3.config.generateHardModulePath(ref);
try {
for (const _ref3 of cmds) {
var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2);
const stage = _ref4[0];
const cmd = _ref4[1];
yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).default)(stage, _this3.config, loc, cmd, spinner);
}
} catch (err) {
err.message = `${loc}: ${err.message}`;
invariant(ref, 'expected reference');
if (ref.optional) {
ref.ignore = true;
_this3.reporter.warn(_this3.reporter.lang('optionalModuleScriptFail', err.message));
_this3.reporter.info(_this3.reporter.lang('optionalModuleFail'));
// Cleanup node_modules
try {
yield (_fs || _load_fs()).unlink(loc);
} catch (e) {
_this3.reporter.error(_this3.reporter.lang('optionalModuleCleanupFail', e.message));
}
} else {
throw err;
}
}
})();
}
packageCanBeInstalled(pkg) {
const cmds = this.getInstallCommands(pkg);
if (!cmds.length) {
return false;
}
const ref = pkg._reference;
invariant(ref, 'Missing package reference');
Iif (!ref.fresh && !this.force) {
// this package hasn't been touched
return false;
}
// we haven't actually written this module out
Iif (ref.ignore) {
return false;
}
return true;
}
runCommand(spinner, pkg) {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const cmds = _this4.getInstallCommands(pkg);
spinner.setPrefix(++_this4.installed, pkg.name);
yield _this4.install(cmds, pkg, spinner);
})();
}
// detect if there is a circularDependency in the dependency tree
detectCircularDependencies(root, seenManifests, pkg) {
const ref = pkg._reference;
invariant(ref, 'expected reference');
const deps = ref.dependencies;
for (const dep of deps) {
const pkgDep = this.resolver.getStrictResolvedPattern(dep);
if (seenManifests.has(pkgDep)) {
// there is a cycle but not with the root
continue;
}
seenManifests.add(pkgDep);
// found a dependency pointing to root
if (pkgDep == root) {
return true;
}
if (this.detectCircularDependencies(root, seenManifests, pkgDep)) {
return true;
}
}
return false;
}
// find the next package to be installed
findInstallablePackage(workQueue, installed) {
for (const pkg of workQueue) {
const ref = pkg._reference;
invariant(ref, 'expected reference');
const deps = ref.dependencies;
let dependenciesFullfilled = true;
for (const dep of deps) {
const pkgDep = this.resolver.getStrictResolvedPattern(dep);
Iif (!installed.has(pkgDep)) {
dependenciesFullfilled = false;
break;
}
}
// all depedencies are installed
Eif (dependenciesFullfilled) {
return pkg;
}
// detect circular dependency, mark this pkg as installable to break the circle
if (this.detectCircularDependencies(pkg, new Set(), pkg)) {
return pkg;
}
}
return null;
}
worker(spinner, workQueue, installed, waitQueue) {
var _this5 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
while (true) {
// No more work to be done
if (workQueue.size == 0) {
break;
}
// find a installable package
const pkg = _this5.findInstallablePackage(workQueue, installed);
// can't find a package to install, register into waitQueue
Iif (pkg == null) {
spinner.clear();
yield new Promise(function (resolve) {
return waitQueue.add(resolve);
});
continue;
}
// found a package to install
workQueue.delete(pkg);
if (_this5.packageCanBeInstalled(pkg)) {
yield _this5.runCommand(spinner, pkg);
}
installed.add(pkg);
for (const workerResolve of waitQueue) {
workerResolve();
}
waitQueue.clear();
}
})();
}
init(seedPatterns) {
var _this6 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const workQueue = new Set();
const installed = new Set();
const pkgs = _this6.resolver.getTopologicalManifests(seedPatterns);
let installablePkgs = 0;
// A map to keep track of what files exist before installation
const beforeFilesMap = new Map();
for (const pkg of pkgs) {
if (_this6.packageCanBeInstalled(pkg)) {
const ref = pkg._reference;
invariant(ref, 'expected reference');
const loc = _this6.config.generateHardModulePath(ref);
beforeFilesMap.set(loc, (yield _this6.walk(loc)));
installablePkgs += 1;
}
workQueue.add(pkg);
}
// waitQueue acts like a semaphore to allow workers to register to be notified
// when there are more work added to the work queue
const waitQueue = new Set();
const workers = [];
const set = _this6.reporter.activitySet(installablePkgs, Math.min((_constants || _load_constants()).CHILD_CONCURRENCY, workQueue.size));
for (const spinner of set.spinners) {
workers.push(_this6.worker(spinner, workQueue, installed, waitQueue));
}
yield Promise.all(workers);
// cache all build artifacts
for (const pkg of pkgs) {
if (_this6.packageCanBeInstalled(pkg)) {
const ref = pkg._reference;
invariant(ref, 'expected reference');
const loc = _this6.config.generateHardModulePath(ref);
const beforeFiles = beforeFilesMap.get(loc);
invariant(beforeFiles, 'files before installation should always be recorded');
yield _this6.saveBuildArtifacts(loc, pkg, beforeFiles, set.spinners[0]);
}
}
set.end();
})();
}
}
exports.default = PackageInstallScripts;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | 1 1 1 1 1 1 1 1 1 1 27 27 27 27 1 27 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 3 1 1 1 1 1 1 1 19 19 19 19 27 27 27 27 27 27 27 173 173 173 173 173 173 173 173 224 224 16 173 173 165 8 8 8 16 16 1 1 1 1 1 1 1 1250 1 1 1 1 1 1 173 173 173 173 173 173 173 173 173 173 173 173 173 173 508 508 1 1 1 2 2 2 2 2 336 336 336 1 168 168 1 1 2 508 508 1 2 1 38 38 1 1 1 1 1 173 173 173 173 173 1 173 1 173 173 173 173 1 1 1 1 1 3 3 3 3 3 3 3 3 3 3 3 3 1 1 1 1 3 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.linkBin = undefined;
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let linkBin = exports.linkBin = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) {
Iif (process.platform === 'win32') {
const unlockMutex = yield (0, (_mutex || _load_mutex()).default)(src);
try {
yield cmdShim(src, dest);
} finally {
unlockMutex();
}
} else {
yield (_fs || _load_fs()).mkdirp(path.dirname(dest));
yield (_fs || _load_fs()).symlink(src, dest);
yield (_fs || _load_fs()).chmod(dest, '755');
}
});
return function linkBin(_x, _x2) {
return _ref.apply(this, arguments);
};
})();
var _packageHoister;
function _load_packageHoister() {
return _packageHoister = _interopRequireDefault(require('./package-hoister.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('./constants.js'));
}
var _promise;
function _load_promise() {
return _promise = _interopRequireWildcard(require('./util/promise.js'));
}
var _misc;
function _load_misc() {
return _misc = require('./util/misc.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('./util/fs.js'));
}
var _mutex;
function _load_mutex() {
return _mutex = _interopRequireDefault(require('./util/mutex.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const cmdShim = (_promise || _load_promise()).promisify(require('cmd-shim'));
const semver = require('semver');
const path = require('path');
class PackageLinker {
constructor(config, resolver) {
this.resolver = resolver;
this.reporter = config.reporter;
this.config = config;
}
linkSelfDependencies(pkg, pkgLoc, targetBinLoc) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
targetBinLoc = yield (_fs || _load_fs()).realpath(targetBinLoc);
pkgLoc = yield (_fs || _load_fs()).realpath(pkgLoc);
for (const _ref2 of (0, (_misc || _load_misc()).entries)(pkg.bin)) {
var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 2);
const scriptName = _ref3[0];
const scriptCmd = _ref3[1];
const dest = path.join(targetBinLoc, scriptName);
const src = path.join(pkgLoc, scriptCmd);
Iif (!(yield (_fs || _load_fs()).exists(src))) {
// TODO maybe throw an error
continue;
}
yield linkBin(src, dest);
}
})();
}
linkBinDependencies(pkg, dir) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const deps = [];
const ref = pkg._reference;
invariant(ref, 'Package reference is missing');
const remote = pkg._remote;
invariant(remote, 'Package remote is missing');
// link up `bin scripts` in `dependencies`
for (const pattern of ref.dependencies) {
const dep = _this.resolver.getStrictResolvedPattern(pattern);
if (dep.bin && Object.keys(dep.bin).length) {
deps.push({ dep, loc: _this.config.generateHardModulePath(dep._reference) });
}
}
// link up the `bin` scripts in bundled dependencies
Iif (pkg.bundleDependencies) {
for (const depName of pkg.bundleDependencies) {
const loc = path.join(_this.config.generateHardModulePath(ref), _this.config.getFolder(pkg), depName);
const dep = yield _this.config.readManifest(loc, remote.registry);
if (dep.bin && Object.keys(dep.bin).length) {
deps.push({ dep, loc });
}
}
}
// no deps to link
if (!deps.length) {
return;
}
// ensure our .bin file we're writing these to exists
const binLoc = path.join(dir, '.bin');
yield (_fs || _load_fs()).mkdirp(binLoc);
// write the executables
for (const _ref4 of deps) {
const dep = _ref4.dep,
loc = _ref4.loc;
yield _this.linkSelfDependencies(dep, loc, binLoc);
}
})();
}
getFlatHoistedTree(patterns) {
const hoister = new (_packageHoister || _load_packageHoister()).default(this.config, this.resolver);
hoister.seed(patterns);
return Promise.resolve(hoister.init());
}
copyModules(patterns, linkDuplicates) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
let flatTree = yield _this2.getFlatHoistedTree(patterns);
// sorted tree makes file creation and copying not to interfere with each other
flatTree = flatTree.sort(function (dep1, dep2) {
return dep1[0].localeCompare(dep2[0]);
});
// list of artifacts in modules to remove from extraneous removal
const artifactFiles = [];
const copyQueue = new Map();
const hardlinkQueue = new Map();
const hardlinksEnabled = linkDuplicates && (yield (_fs || _load_fs()).hardlinksWork(_this2.config.cwd));
const copiedSrcs = new Map();
for (const _ref5 of flatTree) {
var _ref6 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref5, 2);
const dest = _ref6[0];
var _ref6$ = _ref6[1];
const pkg = _ref6$.pkg;
const src = _ref6$.loc;
const ref = pkg._reference;
invariant(ref, 'expected package reference');
ref.setLocation(dest);
// get a list of build artifacts contained in this module so we can prevent them from being marked as
// extraneous
const metadata = yield _this2.config.readPackageMetadata(src);
for (const file of metadata.artifacts) {
artifactFiles.push(path.join(dest, file));
}
const copiedDest = copiedSrcs.get(src);
Eif (!copiedDest) {
Iif (hardlinksEnabled) {
copiedSrcs.set(src, dest);
}
copyQueue.set(dest, {
src,
dest,
onFresh() {
Eif (ref) {
ref.setFresh(true);
}
}
});
} else {
hardlinkQueue.set(dest, {
src: copiedDest,
dest,
onFresh() {
if (ref) {
ref.setFresh(true);
}
}
});
}
}
// keep track of all scoped paths to remove empty scopes after copy
const scopedPaths = new Set();
// register root & scoped packages as being possibly extraneous
const possibleExtraneous = new Set();
for (const folder of _this2.config.registryFolders) {
const loc = path.join(_this2.config.cwd, folder);
Eif (yield (_fs || _load_fs()).exists(loc)) {
const files = yield (_fs || _load_fs()).readdir(loc);
let filepath;
for (const file of files) {
filepath = path.join(loc, file);
Iif (file[0] === '@') {
// it's a scope, not a package
scopedPaths.add(filepath);
const subfiles = yield (_fs || _load_fs()).readdir(filepath);
for (const subfile of subfiles) {
possibleExtraneous.add(path.join(filepath, subfile));
}
} else {
possibleExtraneous.add(filepath);
}
}
}
}
// linked modules
for (const loc of possibleExtraneous) {
const stat = yield (_fs || _load_fs()).lstat(loc);
Iif (stat.isSymbolicLink()) {
possibleExtraneous.delete(loc);
copyQueue.delete(loc);
}
}
//
let tick;
yield (_fs || _load_fs()).copyBulk(Array.from(copyQueue.values()), _this2.reporter, {
possibleExtraneous,
artifactFiles,
ignoreBasenames: [(_constants || _load_constants()).METADATA_FILENAME, (_constants || _load_constants()).TARBALL_FILENAME],
onStart: function (num) {
tick = _this2.reporter.progress(num);
},
onProgress(src) {
Eif (tick) {
tick(src);
}
}
});
yield (_fs || _load_fs()).hardlinkBulk(Array.from(hardlinkQueue.values()), _this2.reporter, {
possibleExtraneous,
artifactFiles,
onStart: function (num) {
tick = _this2.reporter.progress(num);
},
onProgress(src) {
if (tick) {
tick(src);
}
}
});
// remove all extraneous files that weren't in the tree
for (const loc of possibleExtraneous) {
_this2.reporter.verbose(_this2.reporter.lang('verboseFileRemoveExtraneous', loc));
yield (_fs || _load_fs()).unlink(loc);
}
// remove any empty scoped directories
for (const scopedPath of scopedPaths) {
const files = yield (_fs || _load_fs()).readdir(scopedPath);
if (files.length === 0) {
yield (_fs || _load_fs()).unlink(scopedPath);
}
}
//
Eif (_this2.config.binLinks) {
const tickBin = _this2.reporter.progress(flatTree.length);
yield (_promise || _load_promise()).queue(flatTree, (() => {
var _ref7 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref8) {
var _ref9 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref8, 2);
let dest = _ref9[0],
pkg = _ref9[1].pkg;
const binLoc = path.join(dest, _this2.config.getFolder(pkg));
yield _this2.linkBinDependencies(pkg, binLoc);
tickBin(dest);
});
return function (_x3) {
return _ref7.apply(this, arguments);
};
})(), 4);
}
})();
}
resolvePeerModules() {
for (const pkg of this.resolver.getManifests()) {
this._resolvePeerModules(pkg);
}
}
_resolvePeerModules(pkg) {
const peerDeps = pkg.peerDependencies;
Eif (!peerDeps) {
return;
}
const ref = pkg._reference;
invariant(ref, 'Package reference is missing');
for (const name in peerDeps) {
const range = peerDeps[name];
const patterns = this.resolver.patternsByPackage[name] || [];
const foundPattern = patterns.find(pattern => {
const resolvedPattern = this.resolver.getResolvedPattern(pattern);
return resolvedPattern ? this._satisfiesPeerDependency(range, resolvedPattern.version) : false;
});
if (foundPattern) {
ref.addDependencies([foundPattern]);
} else {
const depError = patterns.length > 0 ? 'incorrectPeer' : 'unmetPeer';
const pkgHuman = `${pkg.name}@${pkg.version}`,
depHuman = `${name}@${range}`;
this.reporter.warn(this.reporter.lang(depError, pkgHuman, depHuman));
}
}
}
_satisfiesPeerDependency(range, version) {
return range === '*' || semver.satisfies(version, range, this.config.looseSemver);
}
init(patterns, linkDuplicates) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this3.resolvePeerModules();
yield _this3.copyModules(patterns, linkDuplicates);
yield _this3.saveAll(patterns);
})();
}
save(pattern) {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const resolved = _this4.resolver.getResolvedPattern(pattern);
invariant(resolved, `Couldn't find resolved name/version for ${pattern}`);
const ref = resolved._reference;
invariant(ref, 'Missing reference');
//
const src = _this4.config.generateHardModulePath(ref);
// link bins
Eif (_this4.config.binLinks && resolved.bin && Object.keys(resolved.bin).length && !ref.ignore) {
const folder = _this4.config.modulesFolder || path.join(_this4.config.cwd, _this4.config.getFolder(resolved));
const binLoc = path.join(folder, '.bin');
yield (_fs || _load_fs()).mkdirp(binLoc);
yield _this4.linkSelfDependencies(resolved, src, binLoc);
}
})();
}
saveAll(deps) {
var _this5 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
deps = _this5.resolver.dedupePatterns(deps);
yield (_promise || _load_promise()).queue(deps, function (dep) {
return _this5.save(dep);
});
})();
}
}
exports.default = PackageLinker;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | 1 1 1 1 1 1 173 173 173 173 173 173 173 173 173 173 173 173 173 173 173 173 173 173 508 173 201 201 3 173 201 201 201 201 194 173 21 21 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _misc;
function _load_misc() {
return _misc = require('./util/misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class PackageReference {
constructor(request, info, remote) {
this.resolver = request.resolver;
this.lockfile = request.lockfile;
this.requests = [];
this.config = request.config;
this.registry = remote.registry;
this.version = info.version;
this.name = info.name;
this.uid = info._uid;
this.remote = remote;
this.dependencies = [];
this.permissions = {};
this.patterns = [];
this.optional = null;
this.root = false;
this.ignore = false;
this.fresh = false;
this.location = null;
this.addRequest(request);
}
setFresh(fresh) {
this.fresh = fresh;
}
setLocation(loc) {
return this.location = loc;
}
addRequest(request) {
this.requests.push(request);
if (!request.parentRequest) {
this.root = true;
}
}
prune() {
for (const selfPattern of this.patterns) {
// remove ourselves from the resolver
this.resolver.removePattern(selfPattern);
}
}
addDependencies(deps) {
this.dependencies = this.dependencies.concat(deps);
}
setPermission(key, val) {
this.permissions[key] = val;
}
hasPermission(key) {
if (key in this.permissions) {
return this.permissions[key];
} else {
return false;
}
}
addPattern(pattern, manifest) {
this.resolver.addPattern(pattern, manifest);
this.patterns.push(pattern);
const shrunk = this.lockfile.getLocked(pattern);
Iif (shrunk && shrunk.permissions) {
for (const _ref of (0, (_misc || _load_misc()).entries)(shrunk.permissions)) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const key = _ref2[0];
const perm = _ref2[1];
this.setPermission(key, perm);
}
}
}
addOptional(optional) {
if (this.optional == null) {
// optional is uninitialised
this.optional = optional;
} else Eif (!optional) {
// otherwise, ignore all subsequent optional assignments and only accept ones making
// this not optional
this.optional = false;
}
}
}
exports.default = PackageReference;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 3 1 1 1 201 201 201 201 201 201 201 201 201 603 5403 5403 5403 4 599 201 201 201 201 201 201 201 201 201 2 2 2 2 199 199 199 199 199 199 201 201 201 2 199 199 201 201 201 201 201 201 603 603 603 603 603 603 603 603 603 603 603 603 603 2 2 201 201 201 201 201 201 201 201 201 201 201 201 201 201 28 28 28 28 28 28 173 173 173 173 173 173 173 173 173 173 173 173 219 219 219 173 5 5 5 173 173 173 21 173 173 173 519 173 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _validate;
function _load_validate() {
return _validate = require('./util/normalize-manifest/validate.js');
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('./lockfile/wrapper.js'));
}
var _packageReference;
function _load_packageReference() {
return _packageReference = _interopRequireDefault(require('./package-reference.js'));
}
var _index;
function _load_index() {
return _index = _interopRequireWildcard(require('./resolvers/index.js'));
}
var _index2;
function _load_index2() {
return _index2 = require('./resolvers/index.js');
}
var _errors;
function _load_errors() {
return _errors = require('./errors.js');
}
var _misc;
function _load_misc() {
return _misc = require('./util/misc.js');
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('./constants.js'));
}
var _version;
function _load_version() {
return _version = _interopRequireWildcard(require('./util/version.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('./util/fs.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
const invariant = require('invariant');
const semver = require('semver');
class PackageRequest {
constructor(req, resolver) {
this.parentRequest = req.parentRequest;
this.lockfile = resolver.lockfile;
this.registry = req.registry;
this.reporter = resolver.reporter;
this.resolver = resolver;
this.optional = req.optional;
this.pattern = req.pattern;
this.config = resolver.config;
resolver.usedRegistries.add(req.registry);
}
static getExoticResolver(pattern) {
// TODO make this type more refined
for (const _ref of (0, (_misc || _load_misc()).entries)((_index || _load_index()).exotics)) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const Resolver = _ref2[1];
if (Resolver.isVersion(pattern)) {
return Resolver;
}
}
return null;
}
getParentNames() {
const chain = [];
let request = this.parentRequest;
while (request) {
const info = this.resolver.getStrictResolvedPattern(request.pattern);
chain.unshift(info.name);
request = request.parentRequest;
}
return chain;
}
getLocked(remoteType) {
// always prioritise root lockfile
const shrunk = this.lockfile.getLocked(this.pattern);
Iif (shrunk && shrunk.resolved) {
const resolvedParts = (_version || _load_version()).explodeHashedUrl(shrunk.resolved);
return {
name: shrunk.name,
version: shrunk.version,
_uid: shrunk.uid,
_remote: {
resolved: shrunk.resolved,
type: remoteType,
reference: resolvedParts.url,
hash: resolvedParts.hash,
registry: shrunk.registry
},
optionalDependencies: shrunk.optionalDependencies,
dependencies: shrunk.dependencies
};
} else {
return null;
}
}
/**
* If the input pattern matches a registry one then attempt to find it on the registry.
* Otherwise fork off to an exotic resolver if one matches.
*/
findVersionOnRegistry(pattern) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
var _ref3 = yield _this.normalize(pattern);
const range = _ref3.range,
name = _ref3.name;
const exoticResolver = PackageRequest.getExoticResolver(range);
if (exoticResolver) {
let data = yield _this.findExoticVersionInfo(exoticResolver, range);
// clone data as we're manipulating it in place and this could be resolved multiple
// times
data = Object.assign({}, data);
// this is so the returned package response uses the overridden name. ie. if the
// package's actual name is `bar`, but it's been specified in the manifest like:
// "foo": "http://foo.com/bar.tar.gz"
// then we use the foo name
data.name = name;
return data;
}
const Resolver = _this.getRegistryResolver();
const resolver = new Resolver(_this, name, range);
return resolver.resolve();
})();
}
/**
* Get the registry resolver associated with this package request.
*/
getRegistryResolver() {
const Resolver = (_index2 || _load_index2()).registries[this.registry];
Eif (Resolver) {
return Resolver;
} else {
throw new (_errors || _load_errors()).MessageError(this.reporter.lang('unknownRegistryResolver', this.registry));
}
}
normalizeRange(pattern) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (pattern.includes(':') || pattern.includes('@') || PackageRequest.getExoticResolver(pattern)) {
return Promise.resolve(pattern);
}
Iif (yield (_fs || _load_fs()).exists(path.join(_this2.config.cwd, pattern))) {
return Promise.resolve(`file:${pattern}`);
}
return Promise.resolve(pattern);
})();
}
normalize(pattern) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
var _PackageRequest$norma = PackageRequest.normalizePattern(pattern);
const name = _PackageRequest$norma.name,
range = _PackageRequest$norma.range,
hasVersion = _PackageRequest$norma.hasVersion;
const newRange = yield _this3.normalizeRange(range);
return { name, range: newRange, hasVersion };
})();
}
/**
* Explode and normalize a pattern into it's name and range.
*/
static normalizePattern(pattern) {
let hasVersion = false;
let range = 'latest';
let name = pattern;
// if we're a scope then remove the @ and add it back later
let isScoped = false;
Iif (name[0] === '@') {
isScoped = true;
name = name.slice(1);
}
// take first part as the name
const parts = name.split('@');
Eif (parts.length > 1) {
name = parts.shift();
range = parts.join('@');
Eif (range) {
hasVersion = true;
} else {
range = '*';
}
}
// add back @ scope suffix
Iif (isScoped) {
name = `@${name}`;
}
return { name, range, hasVersion };
}
/**
* Construct an exotic resolver instance with the input `ExoticResolver` and `range`.
*/
findExoticVersionInfo(ExoticResolver, range) {
const resolver = new ExoticResolver(this, range);
return resolver.resolve();
}
/**
* If the current pattern matches an exotic resolver then delegate to it or else try
* the registry.
*/
findVersionInfo() {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const exoticResolver = PackageRequest.getExoticResolver(_this4.pattern);
Iif (exoticResolver) {
return yield _this4.findExoticVersionInfo(exoticResolver, _this4.pattern);
} else {
return yield _this4.findVersionOnRegistry(_this4.pattern);
}
})();
}
reportResolvedRangeMatch(info, resolved) {}
/**
* TODO description
*/
find() {
var _this5 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// find version info for this package pattern
const info = yield _this5.findVersionInfo();
Iif (!info) {
throw new (_errors || _load_errors()).MessageError(_this5.reporter.lang('unknownPackage', _this5.pattern));
}
(0, (_validate || _load_validate()).cleanDependencies)(info, false, _this5.reporter, function () {
// swallow warnings
});
// check if while we were resolving this dep we've already resolved one that satisfies
// the same range
var _PackageRequest$norma2 = PackageRequest.normalizePattern(_this5.pattern);
const range = _PackageRequest$norma2.range,
name = _PackageRequest$norma2.name;
const resolved = _this5.resolver.getHighestRangeVersionMatch(name, range);
if (resolved) {
_this5.reportResolvedRangeMatch(info, resolved);
const ref = resolved._reference;
invariant(ref, 'Resolved package info has no package reference');
ref.addRequest(_this5);
ref.addPattern(_this5.pattern, resolved);
return;
}
Iif (info.flat && !_this5.resolver.flat) {
throw new (_errors || _load_errors()).MessageError(_this5.reporter.lang('flatGlobalError'));
}
// validate version info
PackageRequest.validateVersionInfo(info, _this5.reporter);
//
const remote = info._remote;
invariant(remote, 'Missing remote');
// set package reference
const ref = new (_packageReference || _load_packageReference()).default(_this5, info, remote);
ref.addPattern(_this5.pattern, info);
ref.addOptional(_this5.optional);
info._reference = ref;
info._remote = remote;
// start installation of dependencies
const promises = [];
const deps = [];
// normal deps
for (const depName in info.dependencies) {
const depPattern = depName + '@' + info.dependencies[depName];
deps.push(depPattern);
promises.push(_this5.resolver.find({
pattern: depPattern,
registry: remote.registry,
optional: false,
parentRequest: _this5
}));
}
// optional deps
for (const depName in info.optionalDependencies) {
const depPattern = depName + '@' + info.optionalDependencies[depName];
deps.push(depPattern);
promises.push(_this5.resolver.find({
pattern: depPattern,
registry: remote.registry,
optional: true,
parentRequest: _this5
}));
}
yield Promise.all(promises);
ref.addDependencies(deps);
// Now that we have all dependencies, it's safe to propagate optional
for (const otherRequest of ref.requests.slice(1)) {
ref.addOptional(otherRequest.optional);
}
})();
}
/**
* TODO description
*/
static validateVersionInfo(info, reporter) {
// human readable name to use in errors
const human = `${info.name}@${info.version}`;
info.version = PackageRequest.getPackageVersion(info);
for (const key of (_constants || _load_constants()).REQUIRED_PACKAGE_KEYS) {
Iif (!info[key]) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('missingRequiredPackageKey', human, key));
}
}
}
/**
* Returns the package version if present, else defaults to the uid
*/
static getPackageVersion(info) {
// TODO possibly reconsider this behaviour
return info.version === undefined ? info._uid : info.version;
}
/**
* Gets all of the outdated packages and sorts them appropriately
*/
static getOutdatedPackages(lockfile, install, config, reporter) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
var _ref4 = yield install.fetchRequestFromCwd();
const depReqPatterns = _ref4.requests;
const deps = yield Promise.all(depReqPatterns.map((() => {
var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref6) {
let pattern = _ref6.pattern,
hint = _ref6.hint;
const locked = lockfile.getLocked(pattern);
if (!locked) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('lockfileOutdated'));
}
const name = locked.name,
current = locked.version;
let latest = '';
let wanted = '';
let url = '';
const normalized = PackageRequest.normalizePattern(pattern);
if (PackageRequest.getExoticResolver(pattern) || PackageRequest.getExoticResolver(normalized.range)) {
latest = wanted = 'exotic';
url = normalized.range;
} else {
const registry = config.registries[locked.registry];
var _ref7 = yield registry.checkOutdated(config, name, normalized.range);
latest = _ref7.latest;
wanted = _ref7.wanted;
url = _ref7.url;
}
return { name, current, wanted, latest, url, hint };
});
return function (_x) {
return _ref5.apply(this, arguments);
};
})()));
// Make sure to always output `exotic` versions to be compatible with npm
const isDepOld = function (_ref8) {
let current = _ref8.current,
latest = _ref8.latest,
wanted = _ref8.wanted;
return latest === 'exotic' || latest !== 'exotic' && (semver.lt(current, wanted) || semver.lt(current, latest));
};
const orderByName = function (depA, depB) {
return depA.name.localeCompare(depB.name);
};
return deps.filter(isDepOld).sort(orderByName);
})();
}
}
exports.default = PackageRequest;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 1 1 1 1 1 1 173 173 173 173 173 201 173 3 3 3 9 9 9 9 3 1 1 1 174 227 227 54 173 173 173 173 173 1 1 1 1 173 173 173 1 3 3 3 603 603 84 519 519 3 201 201 201 1687 1675 1675 1675 201 201 170 31 31 38 38 38 31 31 3 28 28 28 227 227 227 227 26 201 201 201 201 201 201 201 1 1 1 1 1 3 1 3 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('./package-request.js'));
}
var _requestManager;
function _load_requestManager() {
return _requestManager = _interopRequireDefault(require('./util/request-manager.js'));
}
var _blockingQueue;
function _load_blockingQueue() {
return _blockingQueue = _interopRequireDefault(require('./util/blocking-queue.js'));
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('./lockfile/wrapper.js'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('./util/map.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const semver = require('semver');
class PackageResolver {
constructor(config, lockfile) {
this.patternsByPackage = (0, (_map || _load_map()).default)();
this.fetchingPatterns = (0, (_map || _load_map()).default)();
this.fetchingQueue = new (_blockingQueue || _load_blockingQueue()).default('resolver fetching');
this.newPatterns = [];
this.patterns = (0, (_map || _load_map()).default)();
this.usedRegistries = new Set();
this.flat = false;
this.reporter = config.reporter;
this.lockfile = lockfile;
this.config = config;
}
// whether the dependency graph will be flattened
// list of registries that have been used in this resolution
// activity monitor
// patterns we've already resolved or are in the process of resolving
// new patterns that didn't exist in the lockfile
// TODO
// these are patterns that the package resolver was seeded with. these are required in
// order to resolve top level peerDependencies
// manages and throttles json api http requests
// list of patterns associated with a package
// lockfile instance which we can use to retrieve version info
// a map of dependency patterns to packages
// reporter instance, abstracts out display logic
// environment specific config methods and options
/**
* TODO description
*/
isNewPattern(pattern) {
return this.newPatterns.indexOf(pattern) >= 0;
}
/**
* TODO description
*/
updateManifest(ref, newPkg) {
// inherit fields
const oldPkg = this.patterns[ref.patterns[0]];
newPkg._reference = ref;
newPkg._remote = ref.remote;
newPkg.name = oldPkg.name;
// update patterns
for (const pattern of ref.patterns) {
this.patterns[pattern] = newPkg;
}
return Promise.resolve();
}
/**
* Given a list of patterns, dedupe them to a list of unique patterns.
*/
dedupePatterns(patterns) {
const deduped = [];
const seen = new Set();
for (const pattern of patterns) {
const info = this.getResolvedPattern(pattern);
Iif (seen.has(info)) {
continue;
}
seen.add(info);
deduped.push(pattern);
}
return deduped;
}
/**
* Get a list of all manifests by topological order.
*/
getTopologicalManifests(seedPatterns) {
const pkgs = new Set();
const skip = new Set();
const add = seedPatterns => {
for (const pattern of seedPatterns) {
const pkg = this.getStrictResolvedPattern(pattern);
if (skip.has(pkg)) {
continue;
}
const ref = pkg._reference;
invariant(ref, 'expected reference');
skip.add(pkg);
add(ref.dependencies);
pkgs.add(pkg);
}
};
add(seedPatterns);
return pkgs;
}
/**
* Get a list of all manifests by level sort order.
*/
getLevelOrderManifests(seedPatterns) {
const pkgs = new Set();
const skip = new Set();
const add = seedPatterns => {
const refs = [];
for (const pattern of seedPatterns) {
const pkg = this.getStrictResolvedPattern(pattern);
if (skip.has(pkg)) {
continue;
}
const ref = pkg._reference;
invariant(ref, 'expected reference');
refs.push(ref);
skip.add(pkg);
pkgs.add(pkg);
}
for (const ref of refs) {
add(ref.dependencies);
}
};
add(seedPatterns);
return pkgs;
}
/**
* Get a list of all package names in the depenency graph.
*/
getAllDependencyNamesByLevelOrder(seedPatterns) {
const names = new Set();
for (const _ref of this.getLevelOrderManifests(seedPatterns)) {
const name = _ref.name;
names.add(name);
}
return names;
}
/**
* Retrieve all the package info stored for this package name.
*/
getAllInfoForPackageName(name) {
const infos = [];
const seen = new Set();
for (const pattern of this.patternsByPackage[name]) {
const info = this.patterns[pattern];
if (seen.has(info)) {
continue;
}
seen.add(info);
infos.push(info);
}
return infos;
}
/**
* Get a flat list of all package references.
*/
getPackageReferences() {
const refs = [];
for (const manifest of this.getManifests()) {
const ref = manifest._reference;
Eif (ref) {
refs.push(ref);
}
}
return refs;
}
/**
* Get a flat list of all package info.
*/
getManifests() {
const infos = [];
const seen = new Set();
for (const pattern in this.patterns) {
const info = this.patterns[pattern];
if (seen.has(info)) {
continue;
}
infos.push(info);
seen.add(info);
}
return infos;
}
/**
* replace pattern in resolver, e.g. `name` is replaced with `name@^1.0.1`
*/
replacePattern(pattern, newPattern) {
const pkg = this.getResolvedPattern(pattern);
invariant(pkg, `missing package ${pattern}`);
const ref = pkg._reference;
invariant(ref, 'expected package reference');
ref.patterns = [newPattern];
this.newPatterns.splice(this.newPatterns.indexOf(pattern), 1, newPattern);
this.addPattern(newPattern, pkg);
this.removePattern(pattern);
}
/**
* Make all versions of this package resolve to it.
*/
collapseAllVersionsOfPackage(name, version) {
const patterns = this.dedupePatterns(this.patternsByPackage[name]);
const human = `${name}@${version}`;
// get manifest that matches the version we're collapsing too
let collapseToReference;
let collapseToManifest;
let collapseToPattern;
for (const pattern of patterns) {
const _manifest = this.patterns[pattern];
if (_manifest.version === version) {
collapseToReference = _manifest._reference;
collapseToManifest = _manifest;
collapseToPattern = pattern;
break;
}
}
invariant(collapseToReference && collapseToManifest && collapseToPattern, `Couldn't find package manifest for ${human}`);
for (const pattern of patterns) {
// don't touch the pattern we're collapsing to
if (pattern === collapseToPattern) {
continue;
}
// remove this pattern
const ref = this.getStrictResolvedPattern(pattern)._reference;
invariant(ref, 'expected package reference');
const refPatterns = ref.patterns.slice();
ref.prune();
// add pattern to the manifest we're collapsing to
for (const pattern of refPatterns) {
collapseToReference.addPattern(pattern, collapseToManifest);
}
}
return collapseToPattern;
}
/**
* TODO description
*/
addPattern(pattern, info) {
this.patterns[pattern] = info;
const byName = this.patternsByPackage[info.name] = this.patternsByPackage[info.name] || [];
byName.push(pattern);
}
/**
* TODO description
*/
removePattern(pattern) {
const pkg = this.patterns[pattern];
if (!pkg) {
return;
}
const byName = this.patternsByPackage[pkg.name];
if (!byName) {
return;
}
byName.splice(byName.indexOf(pattern), 1);
delete this.patterns[pattern];
}
/**
* TODO description
*/
getResolvedPattern(pattern) {
return this.patterns[pattern];
}
/**
* TODO description
*/
getStrictResolvedPattern(pattern) {
const manifest = this.getResolvedPattern(pattern);
invariant(manifest, 'expected manifest');
return manifest;
}
/**
* TODO description
*/
getExactVersionMatch(name, version) {
const patterns = this.patternsByPackage[name];
if (!patterns) {
return null;
}
for (const pattern of patterns) {
const info = this.getStrictResolvedPattern(pattern);
if (info.version === version) {
return info;
}
}
return null;
}
/**
* Get the manifest of the highest known version that satisfies a package range
*/
getHighestRangeVersionMatch(name, range) {
const patterns = this.patternsByPackage[name];
if (!patterns) {
return null;
}
const versionNumbers = [];
const resolvedPatterns = patterns.map(pattern => {
const info = this.getStrictResolvedPattern(pattern);
versionNumbers.push(info.version);
return info;
});
const maxValidRange = semver.maxSatisfying(versionNumbers, range);
if (!maxValidRange) {
return null;
}
const indexOfmaxValidRange = versionNumbers.indexOf(maxValidRange);
const maxValidRangeManifest = resolvedPatterns[indexOfmaxValidRange];
return maxValidRangeManifest;
}
/**
* TODO description
*/
find(req) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const fetchKey = `${req.registry}:${req.pattern}`;
if (_this.fetchingPatterns[fetchKey]) {
return;
} else {
_this.fetchingPatterns[fetchKey] = true;
}
Eif (_this.activity) {
_this.activity.tick(req.pattern);
}
Eif (!_this.lockfile.getLocked(req.pattern, true)) {
_this.newPatterns.push(req.pattern);
}
const request = new (_packageRequest || _load_packageRequest()).default(req, _this);
yield request.find();
})();
}
/**
* TODO description
*/
init(deps, isFlat) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this2.flat = isFlat;
//
const activity = _this2.activity = _this2.reporter.activity();
//
_this2.seedPatterns = deps.map(function (dep) {
return dep.pattern;
});
//
yield Promise.all(deps.map(function (req) {
return _this2.find(req);
}));
activity.end();
_this2.activity = null;
})();
}
}
exports.default = PackageResolver;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| aliases.js | 100% | (9 / 9) | 83.33% | (5 / 6) | 100% | (2 / 2) | 100% | (8 / 8) | |
| index.js | 52.94% | (135 / 255) | 37.79% | (65 / 172) | 53.33% | (8 / 15) | 54.55% | (132 / 242) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const shorthands = {
c: 'config',
i: 'install',
la: 'list',
ll: 'list',
ln: 'link',
ls: 'list',
r: 'remove',
rb: 'rebuild',
rm: 'remove',
t: 'test',
tst: 'test',
un: 'remove',
up: 'upgrade',
v: 'version'
};
const affordances = {
'add-user': 'login',
adduser: 'login',
author: 'owner',
'dist-tag': 'tag',
'dist-tags': 'tag',
isntall: 'install',
'run-script': 'run',
runScript: 'run',
show: 'info',
uninstall: 'remove',
update: 'upgrade',
verison: 'version',
view: 'info'
};
exports.default = (0, (_extends2 || _load_extends()).default)({}, shorthands, affordances);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
var _index;
function _load_index() {
return _index = require('../reporters/index.js');
}
var _index2;
function _load_index2() {
return _index2 = require('../registries/index.js');
}
var _index3;
function _load_index3() {
return _index3 = _interopRequireWildcard(require('./commands/index.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _network;
function _load_network() {
return _network = _interopRequireWildcard(require('../util/network.js'));
}
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _aliases;
function _load_aliases() {
return _aliases = _interopRequireDefault(require('./aliases.js'));
}
var _config;
function _load_config() {
return _config = _interopRequireDefault(require('../config.js'));
}
var _misc;
function _load_misc() {
return _misc = require('../util/misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
const chalk = require('chalk');
const commander = require('commander');
const fs = require('fs');
const invariant = require('invariant');
const lockfile = require('proper-lockfile');
const loudRejection = require('loud-rejection');
const net = require('net');
const onDeath = require('death');
const path = require('path');
const pkg = require('../../package.json');
loudRejection();
//
const startArgs = process.argv.slice(0, 2);
let args = process.argv.slice(2);
// ignore all arguments after a --
let endArgs = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--') {
endArgs = args.slice(i + 1);
args = args.slice(0, i);
}
}
// NOTE: Pending resolution of https://github.com/tj/commander.js/issues/346
// Remove this (and subsequent use in the logic below) after bug is resolved and issue is closed
const ARGS_THAT_SHARE_NAMES_WITH_OPTIONS = ['version'];
// set global options
commander.version(pkg.version);
commander.usage('[command] [flags]');
commander.option('--verbose', 'output verbose messages on internal operations');
commander.option('--offline', 'trigger an error if any required dependencies are not available in local cache');
commander.option('--prefer-offline', 'use network only if dependencies are not available in local cache');
commander.option('--strict-semver');
commander.option('--json', '');
commander.option('--ignore-scripts', "don't run lifecycle scripts");
commander.option('--har', 'save HAR output of network traffic');
commander.option('--ignore-platform', 'ignore platform checks');
commander.option('--ignore-engines', 'ignore engines check');
commander.option('--ignore-optional', 'ignore optional dependencies');
commander.option('--force', 'install and build scripts even if they were built before, overwrite lockfile');
commander.option('--skip-integrity-check', 'run install without checking if node_modules is installed');
commander.option('--no-bin-links', "don't generate bin links when setting up packages");
commander.option('--flat', 'only allow one version of a package');
commander.option('--prod, --production [prod]', '');
commander.option('--no-lockfile', "don't read or generate a lockfile");
commander.option('--pure-lockfile', "don't generate a lockfile");
commander.option('--frozen-lockfile', "don't generate a lockfile and fail if an update is needed");
commander.option('--link-duplicates', 'create hardlinks to the repeated modules in node_modules');
commander.option('--global-folder <path>', '');
commander.option('--modules-folder <path>', 'rather than installing modules into the node_modules folder relative to the cwd, output them here');
commander.option('--cache-folder <path>', 'specify a custom folder to store the yarn cache');
commander.option('--mutex <type>[:specifier]', 'use a mutex to ensure only one yarn instance is executing');
commander.option('--no-emoji', 'disable emoji in output');
commander.option('--proxy <host>', '');
commander.option('--https-proxy <host>', '');
commander.option('--no-progress', 'disable progress bar');
commander.option('--network-concurrency <number>', 'maximum number of concurrent network requests', parseInt);
commander.option('--non-interactive', 'do not show interactive prompts');
// get command name
let commandName = args.shift() || '';
let command;
//
const getDocsLink = name => `${(_constants || _load_constants()).YARN_DOCS}${name || ''}`;
const getDocsInfo = name => 'Visit ' + chalk.bold(getDocsLink(name)) + ' for documentation about this command.';
//
Iif (commandName === '--help' || commandName === '-h') {
commandName = 'help';
}
// if no args or command name looks like a flag then default to `install`
Eif (!commandName || commandName[0] === '-') {
Iif (commandName) {
args.unshift(commandName);
}
commandName = 'install';
}
// aliases: i -> install
Iif (commandName && typeof (_aliases || _load_aliases()).default[commandName] === 'string') {
const alias = (_aliases || _load_aliases()).default[commandName];
command = {
run(config, reporter) {
throw new (_errors || _load_errors()).MessageError(`Did you mean \`yarn ${alias}\`?`);
}
};
}
//
Iif (commandName === 'help' && args.length) {
commandName = (0, (_misc || _load_misc()).camelCase)(args.shift());
args.push('--help');
}
//
invariant(commandName, 'Missing command name');
Eif (!command) {
const camelised = (0, (_misc || _load_misc()).camelCase)(commandName);
Eif (camelised) {
command = (_index3 || _load_index3())[camelised];
}
}
//
Eif (command && typeof command.setFlags === 'function') {
command.setFlags(commander);
}
Iif (args.indexOf('--help') >= 0 || args.indexOf('-h') >= 0) {
const examples = command && command.examples || [];
if (examples.length) {
commander.on('--help', () => {
console.log(' Examples:\n');
for (const example of examples) {
console.log(` $ yarn ${example}`);
}
console.log();
});
}
commander.on('--help', () => console.log(' ' + getDocsInfo(commandName) + '\n'));
commander.parse(startArgs.concat(args));
commander.help();
process.exit(1);
}
// parse flags
args.unshift(commandName);
Iif (ARGS_THAT_SHARE_NAMES_WITH_OPTIONS.indexOf(commandName) >= 0 && args[0] === commandName) {
args.shift();
}
commander.parse(startArgs.concat(args));
commander.args = commander.args.concat(endArgs);
Eif (command) {
commander.args.shift();
} else {
command = (_index3 || _load_index3()).run;
}
invariant(command, 'missing command');
//
let Reporter = (_index || _load_index()).ConsoleReporter;
Iif (commander.json) {
Reporter = (_index || _load_index()).JSONReporter;
}
const reporter = new Reporter({
emoji: commander.emoji && process.stdout.isTTY && process.platform === 'darwin',
verbose: commander.verbose,
noProgress: !commander.progress
});
reporter.initPeakMemoryCounter();
//
const config = new (_config || _load_config()).default(reporter);
// print header
let outputWrapper = true;
Iif (typeof command.hasWrapper === 'function') {
outputWrapper = command.hasWrapper(commander, commander.args);
}
Iif (commander.json) {
outputWrapper = false;
}
Eif (outputWrapper && commandName !== 'help') {
reporter.header(commandName, pkg);
}
Iif (command.noArguments && commander.args.length) {
reporter.error(reporter.lang('noArguments'));
reporter.info(getDocsInfo(commandName));
process.exit(1);
}
//
Iif (commander.yes) {
reporter.warn(reporter.lang('yesWarning'));
}
//
Iif (!commander.offline && (_network || _load_network()).isOffline()) {
reporter.warn(reporter.lang('networkWarning'));
}
//
Iif (command.requireLockfile && !fs.existsSync(path.join(config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME))) {
reporter.error(reporter.lang('noRequiredLockfile'));
process.exit(1);
}
//
const run = () => {
invariant(command, 'missing command');
return command.run(config, reporter, commander, commander.args).then(() => {
reporter.close();
Eif (outputWrapper) {
reporter.footer(false);
}
});
};
//
const runEventuallyWithFile = (mutexFilename, isFirstTime) => {
return new Promise(ok => {
const lockFilename = mutexFilename || path.join(config.cwd, (_constants || _load_constants()).SINGLE_INSTANCE_FILENAME);
lockfile.lock(lockFilename, { realpath: false }, (err, release) => {
if (err) {
if (isFirstTime) {
reporter.warn(reporter.lang('waitingInstance'));
}
setTimeout(() => {
ok(runEventuallyWithFile(mutexFilename, isFirstTime));
}, 200); // do not starve the CPU
} else {
onDeath(() => {
process.exit(1);
});
ok(run().then(release));
}
});
});
};
//
const runEventuallyWithNetwork = mutexPort => {
return new Promise(ok => {
const connectionOptions = {
port: +mutexPort || (_constants || _load_constants()).SINGLE_INSTANCE_PORT
};
const server = net.createServer();
server.on('error', () => {
// another Yarn instance exists, let's connect to it to know when it dies.
reporter.warn(reporter.lang('waitingInstance'));
const socket = net.createConnection(connectionOptions);
socket.on('connect', () => {
// Allow the program to exit if this is the only active server in the event system.
socket.unref();
}).on('close', hadError => {
// the `close` event gets always called after the `error` event
if (!hadError) {
process.nextTick(() => {
ok(runEventuallyWithNetwork(mutexPort));
});
}
}).on('error', () => {
// No server to listen to ? Let's retry to become the next server then.
process.nextTick(() => {
ok(runEventuallyWithNetwork(mutexPort));
});
});
});
const onServerEnd = () => {
server.close();
return Promise.resolve();
};
// open the server and continue only if succeed.
server.listen(connectionOptions, () => {
// ensure the server gets closed properly on SIGNALS.
onDeath(onServerEnd);
ok(run().then(onServerEnd));
});
});
};
function onUnexpectedError(err) {
function indent(str) {
return '\n ' + str.trim().split('\n').join('\n ');
}
const log = [];
log.push(`Arguments: ${indent(process.argv.join(' '))}`);
log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`);
log.push(`Yarn version: ${indent(pkg.version)}`);
log.push(`Node version: ${indent(process.versions.node)}`);
log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`);
// add manifests
for (const registryName of (_index2 || _load_index2()).registryNames) {
const possibleLoc = path.join(config.cwd, (_index2 || _load_index2()).registries[registryName].filename);
const manifest = fs.existsSync(possibleLoc) ? fs.readFileSync(possibleLoc, 'utf8') : 'No manifest';
log.push(`${registryName} manifest: ${indent(manifest)}`);
}
// lockfile
const lockLoc = path.join(config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME);
const lockfile = fs.existsSync(lockLoc) ? fs.readFileSync(lockLoc, 'utf8') : 'No lockfile';
log.push(`Lockfile: ${indent(lockfile)}`);
log.push(`Trace: ${indent(err.stack)}`);
const errorReportLoc = writeErrorReport(log);
reporter.error(reporter.lang('unexpectedError', err.message));
if (errorReportLoc) {
reporter.info(reporter.lang('bugReport', errorReportLoc));
}
}
function writeErrorReport(log) {
const errorReportLoc = path.join(config.cwd, 'yarn-error.log');
try {
fs.writeFileSync(errorReportLoc, log.join('\n\n') + '\n');
} catch (err) {
reporter.error(reporter.lang('fileWriteError', errorReportLoc, err.message));
return undefined;
}
return errorReportLoc;
}
//
config.init({
binLinks: commander.binLinks,
modulesFolder: commander.modulesFolder,
globalFolder: commander.globalFolder,
cacheRootFolder: commander.cacheFolder,
preferOffline: commander.preferOffline,
captureHar: commander.har,
ignorePlatform: commander.ignorePlatform,
ignoreEngines: commander.ignoreEngines,
ignoreScripts: commander.ignoreScripts,
offline: commander.preferOffline || commander.offline,
looseSemver: !commander.strictSemver,
production: commander.production,
httpProxy: commander.proxy,
httpsProxy: commander.httpsProxy,
networkConcurrency: commander.networkConcurrency,
nonInteractive: commander.nonInteractive,
commandName
}).then(() => {
// option "no-progress" stored in yarn config
const noProgressConfig = config.registries.yarn.getOption('no-progress');
Iif (noProgressConfig) {
reporter.disableProgress();
}
const exit = () => {
process.exit(0);
};
// verbose logs outputs process.uptime() with this line we can sync uptime to absolute time on the computer
reporter.verbose(`current time: ${new Date().toISOString()}`);
const mutex = commander.mutex;
Iif (mutex && typeof mutex === 'string') {
const parts = mutex.split(':');
const mutexType = parts.shift();
const mutexSpecifier = parts.join(':');
if (mutexType === 'file') {
return runEventuallyWithFile(mutexSpecifier, true).then(exit);
} else if (mutexType === 'network') {
return runEventuallyWithNetwork(mutexSpecifier).then(exit);
} else {
throw new (_errors || _load_errors()).MessageError(`Unknown single instance type ${mutexType}`);
}
} else {
return run().then(exit);
}
}).catch(err => {
reporter.verbose(err.stack);
if (err instanceof (_errors || _load_errors()).MessageError) {
reporter.error(err.message);
} else {
onUnexpectedError(err);
}
if (commandName) {
const actualCommandForHelp = (_index3 || _load_index3())[commandName] ? commandName : (_aliases || _load_aliases()).default[commandName];
if (command && actualCommandForHelp) {
reporter.info(getDocsInfo(actualCommandForHelp));
}
}
process.exit(1);
});
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| _build-sub-commands.js | 60% | (21 / 35) | 39.29% | (11 / 28) | 50% | (4 / 8) | 58.82% | (20 / 34) | |
| _useless.js | 71.43% | (5 / 7) | 0% | (0 / 2) | 33.33% | (1 / 3) | 71.43% | (5 / 7) | |
| access.js | 61.11% | (11 / 18) | 83.33% | (5 / 6) | 22.22% | (2 / 9) | 58.82% | (10 / 17) | |
| add.js | 22.52% | (25 / 111) | 10.61% | (7 / 66) | 12.5% | (3 / 24) | 21.82% | (24 / 110) | |
| bin.js | 64.29% | (9 / 14) | 0% | (0 / 6) | 0% | (0 / 4) | 69.23% | (9 / 13) | |
| cache.js | 34.43% | (21 / 61) | 10.64% | (5 / 47) | 14.29% | (2 / 14) | 39.22% | (20 / 51) | |
| check.js | 15.95% | (37 / 232) | 5.38% | (7 / 130) | 10% | (2 / 20) | 16.29% | (36 / 221) | |
| clean.js | 32.1% | (26 / 81) | 12.5% | (6 / 48) | 18.18% | (2 / 11) | 35.21% | (25 / 71) | |
| config.js | 38.3% | (18 / 47) | 31.82% | (7 / 22) | 30% | (3 / 10) | 36.96% | (17 / 46) | |
| generate-lock-entry.js | 52.5% | (21 / 40) | 20.83% | (5 / 24) | 22.22% | (2 / 9) | 51.28% | (20 / 39) | |
| global.js | 31.46% | (56 / 178) | 11.46% | (11 / 96) | 9.76% | (4 / 41) | 32.74% | (55 / 168) | |
| help.js | 26.19% | (11 / 42) | 0% | (0 / 30) | 0% | (0 / 5) | 36.67% | (11 / 30) | |
| import.js | 24.79% | (58 / 234) | 10.4% | (13 / 125) | 10.91% | (6 / 55) | 25.45% | (57 / 224) | |
| index.js | 95.39% | (145 / 152) | 90.48% | (76 / 84) | 100% | (36 / 36) | 100% | (142 / 142) | |
| info.js | 25.4% | (16 / 63) | 13.16% | (5 / 38) | 25% | (2 / 8) | 24.19% | (15 / 62) | |
| init.js | 27.45% | (28 / 102) | 8.33% | (6 / 72) | 15.38% | (2 / 13) | 29.35% | (27 / 92) | |
| install.js | 59.24% | (279 / 471) | 38.98% | (115 / 295) | 75.95% | (60 / 79) | 59.87% | (276 / 461) | |
| licenses.js | 26.79% | (30 / 112) | 11.29% | (7 / 62) | 17.65% | (3 / 17) | 26.13% | (29 / 111) | |
| link.js | 29.33% | (22 / 75) | 11.11% | (6 / 54) | 20% | (2 / 10) | 32.31% | (21 / 65) | |
| list.js | 24.19% | (30 / 124) | 8.11% | (6 / 74) | 13.33% | (2 / 15) | 23.77% | (29 / 122) | |
| login.js | 26.39% | (19 / 72) | 18.42% | (7 / 38) | 14.29% | (2 / 14) | 25.35% | (18 / 71) | |
| logout.js | 76.92% | (10 / 13) | 83.33% | (5 / 6) | 50% | (2 / 4) | 75% | (9 / 12) | |
| outdated.js | 45.24% | (19 / 42) | 25% | (5 / 20) | 16.67% | (2 / 12) | 43.9% | (18 / 41) | |
| owner.js | 26.21% | (27 / 103) | 10.94% | (7 / 64) | 21.43% | (3 / 14) | 26% | (26 / 100) | |
| pack.js | 28.32% | (32 / 113) | 13.64% | (9 / 66) | 17.65% | (3 / 17) | 30.1% | (31 / 103) | |
| publish.js | 31.48% | (34 / 108) | 8% | (6 / 75) | 12.5% | (2 / 16) | 33.67% | (33 / 98) | |
| remove.js | 37.35% | (31 / 83) | 11.36% | (5 / 44) | 14.29% | (2 / 14) | 41.1% | (30 / 73) | |
| run.js | 24.53% | (26 / 106) | 9.62% | (5 / 52) | 12.5% | (2 / 16) | 26.04% | (25 / 96) | |
| tag.js | 29.17% | (28 / 96) | 10% | (7 / 70) | 18.75% | (3 / 16) | 28.42% | (27 / 95) | |
| team.js | 43.01% | (40 / 93) | 32% | (16 / 50) | 25% | (6 / 24) | 42.39% | (39 / 92) | |
| unlink.js | 35.71% | (20 / 56) | 10.42% | (5 / 48) | 22.22% | (2 / 9) | 41.3% | (19 / 46) | |
| upgrade-interactive.js | 24.77% | (27 / 109) | 14.29% | (6 / 42) | 6.45% | (2 / 31) | 24.07% | (26 / 108) | |
| upgrade.js | 54.29% | (19 / 35) | 20.83% | (5 / 24) | 22.22% | (2 / 9) | 52.94% | (18 / 34) | |
| version.js | 26.83% | (33 / 123) | 7.32% | (6 / 82) | 10% | (2 / 20) | 28.32% | (32 / 113) | |
| versions.js | 61.11% | (11 / 18) | 45.45% | (5 / 11) | 50% | (2 / 4) | 58.82% | (10 / 17) | |
| why.js | 19.89% | (37 / 186) | 6.73% | (7 / 104) | 9.09% | (2 / 22) | 20.69% | (36 / 174) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 1 1 1 1 1 8 8 8 8 8 1 8 18 8 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
exports.default = function (rootCommandName, subCommands) {
let run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
const subName = (0, (_misc || _load_misc()).camelCase)(args.shift() || '');
if (subName && subCommands[subName]) {
const command = subCommands[subName];
const res = yield command(config, reporter, flags, args);
if (res !== false) {
return Promise.resolve();
}
}
if (usage && usage.length) {
reporter.error(`${reporter.lang('usage')}:`);
for (const msg of usage) {
reporter.error(`yarn ${rootCommandName} ${msg}`);
}
}
return Promise.reject(new (_errors || _load_errors()).MessageError(reporter.lang('invalidCommand', subCommandNames.join(', '))));
});
return function run(_x2, _x3, _x4, _x5) {
return _ref.apply(this, arguments);
};
})();
let usage = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
const subCommandNames = Object.keys(subCommands).map((_misc || _load_misc()).hyphenate);
function setFlags(commander) {
commander.usage(`${rootCommandName} [${subCommandNames.join('|')}] [flags]`);
}
const examples = usage.map(cmd => {
return `${rootCommandName} ${cmd}`;
});
return { run, setFlags, examples };
};
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _misc;
function _load_misc() {
return _misc = require('../../util/misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 1 1 3 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (message) {
return {
useless: true,
run() {
throw new (_errors || _load_errors()).MessageError(message);
}
};
};
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setFlags = exports.run = undefined;
var _buildSubCommands2;
function _load_buildSubCommands() {
return _buildSubCommands2 = _interopRequireDefault(require('./_build-sub-commands.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('access', {
public() {
return Promise.reject(new Error('TODO'));
},
restricted() {
return Promise.reject(new Error('TODO'));
},
grant() {
return Promise.reject(new Error('TODO'));
},
revoke() {
return Promise.reject(new Error('TODO'));
},
lsPackages() {
return Promise.reject(new Error('TODO'));
},
lsCollaborators() {
return Promise.reject(new Error('TODO'));
},
edit() {
return Promise.reject(new Error('TODO'));
}
}, ['access public [<package>]', 'access restricted [<package>]', 'access grant <read-only|read-write> <scope:team> [<package>]', 'access revoke <scope:team> [<package>]', 'access ls-packages [<user>|<scope>|<scope:team>]', 'access ls-collaborators [<package> [<user>]]', 'access edit [<package>]']);
const run = _buildSubCommands.run,
setFlags = _buildSubCommands.setFlags;
exports.run = run;
exports.setFlags = setFlags;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.Add = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
if (!args.length) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('missingAddDependencies'));
}
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd, reporter);
yield (0, (_install || _load_install()).wrapLifecycle)(config, flags, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const install = new Add(args, flags, config, reporter, lockfile);
yield install.init();
}));
});
return function run(_x, _x2, _x3, _x4) {
return _ref2.apply(this, arguments);
};
})();
exports.setFlags = setFlags;
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('../../package-request.js'));
}
var _list;
function _load_list() {
return _list = require('./list.js');
}
var _install;
function _load_install() {
return _install = require('./install.js');
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
class Add extends (_install || _load_install()).Install {
constructor(args, flags, config, reporter, lockfile) {
super(flags, config, reporter, lockfile);
this.args = args;
// only one flag is supported, so we can figure out which one was passed to `yarn add`
this.flagToOrigin = [flags.dev && 'devDependencies', flags.optional && 'optionalDependencies', flags.peer && 'peerDependencies', 'dependencies'].filter(Boolean).shift();
}
/**
* TODO
*/
prepareRequests(requests) {
const requestsWithArgs = requests.slice();
for (const pattern of this.args) {
requestsWithArgs.push({
pattern,
registry: 'npm',
optional: false
});
}
return requestsWithArgs;
}
/**
* returns version for a pattern based on Manifest
*/
getPatternVersion(pattern, pkg) {
var _flags = this.flags;
const exact = _flags.exact,
tilde = _flags.tilde;
const parts = (_packageRequest || _load_packageRequest()).default.normalizePattern(pattern);
let version;
if ((_packageRequest || _load_packageRequest()).default.getExoticResolver(pattern)) {
// wasn't a name/range tuple so this is just a raw exotic pattern
version = pattern;
} else if (parts.hasVersion && parts.range) {
// if the user specified a range then use it verbatim
version = parts.range === 'latest' ? `^${pkg.version}` : parts.range;
} else if (tilde) {
// --save-tilde
version = `~${pkg.version}`;
} else if (exact) {
// --save-exact
version = pkg.version;
} else {
// default to save prefix
version = `${String(this.config.getOption('save-prefix') || '')}${pkg.version}`;
}
return version;
}
preparePatterns(patterns) {
const preparedPatterns = patterns.slice();
for (const pattern of this.resolver.dedupePatterns(this.args)) {
const pkg = this.resolver.getResolvedPattern(pattern);
invariant(pkg, `missing package ${pattern}`);
const version = this.getPatternVersion(pattern, pkg);
const newPattern = `${pkg.name}@${version}`;
preparedPatterns.push(newPattern);
this.addedPatterns.push(newPattern);
if (newPattern === pattern) {
continue;
}
this.resolver.replacePattern(pattern, newPattern);
}
return preparedPatterns;
}
bailout(patterns) {
return Promise.resolve(false);
}
/**
* Description
*/
init() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this.addedPatterns = [];
const patterns = yield (_install || _load_install()).Install.prototype.init.call(_this);
yield _this.maybeOutputSaveTree(patterns);
yield _this.savePackages();
return patterns;
})();
}
/**
* Description
*/
fetchRequestFromCwd() {
return (_install || _load_install()).Install.prototype.fetchRequestFromCwd.call(this, this.args);
}
/**
* Output a tree of any newly added dependencies.
*/
maybeOutputSaveTree(patterns) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// don't limit the shown tree depth
const opts = {
reqDepth: 0
};
var _ref = yield (0, (_list || _load_list()).buildTree)(_this2.resolver, _this2.linker, patterns, opts, true, true);
const trees = _ref.trees,
count = _ref.count;
_this2.reporter.success(count === 1 ? _this2.reporter.lang('savedNewDependency') : _this2.reporter.lang('savedNewDependencies', count));
_this2.reporter.tree('newDependencies', trees);
})();
}
/**
* Save added packages to manifest if any of the --save flags were used.
*/
savePackages() {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// fill rootPatternsToOrigin without `excludePatterns`
yield (_install || _load_install()).Install.prototype.fetchRequestFromCwd.call(_this3);
const patternOrigins = Object.keys(_this3.rootPatternsToOrigin);
// get all the different registry manifests in this folder
const manifests = yield _this3.config.getRootManifests();
// add new patterns to their appropriate registry manifest
for (const pattern of _this3.addedPatterns) {
const pkg = _this3.resolver.getResolvedPattern(pattern);
invariant(pkg, `missing package ${pattern}`);
const version = _this3.getPatternVersion(pattern, pkg);
const ref = pkg._reference;
invariant(ref, 'expected package reference');
// lookup the package to determine dependency type; used during `yarn upgrade`
const depType = patternOrigins.reduce(function (acc, prev) {
if (prev.indexOf(`${pkg.name}@`) === 0) {
return _this3.rootPatternsToOrigin[prev];
}
return acc;
}, null);
// depType is calculated when `yarn upgrade` command is used
const target = depType || _this3.flagToOrigin;
// add it to manifest
const object = manifests[ref.registry].object;
object[target] = object[target] || {};
object[target][pkg.name] = version;
}
yield _this3.config.saveRootManifests(manifests);
})();
}
}
exports.Add = Add;
function setFlags(commander) {
commander.usage('add [packages ...] [flags]');
commander.option('-D, --dev', 'save package to your `devDependencies`');
commander.option('-P, --peer', 'save package to your `peerDependencies`');
commander.option('-O, --optional', 'save package to your `optionalDependencies`');
commander.option('-E, --exact', 'install exact version');
commander.option('-T, --tilde', 'install most recent release with the same minor version');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hasWrapper = hasWrapper;
exports.run = run;
var _yarnResolver;
function _load_yarnResolver() {
return _yarnResolver = _interopRequireDefault(require('../../resolvers/registries/yarn-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
function hasWrapper() {}
function run(config, reporter, flags, args) {
const binFolder = path.join(config.cwd, config.registries[(_yarnResolver || _load_yarnResolver()).default.registry].folder, '.bin');
console.log(binFolder);
return Promise.resolve();
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setFlags = exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
exports.hasWrapper = hasWrapper;
var _buildSubCommands2;
function _load_buildSubCommands() {
return _buildSubCommands2 = _interopRequireDefault(require('./_build-sub-commands.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _constants;
function _load_constants() {
return _constants = require('../../constants');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
function hasWrapper(flags, args) {
return args[0] !== 'dir';
}
var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('cache', {
ls(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
let readCacheMetadata = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
let parentDir = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : config.cacheFolder;
let metadataFile = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_constants || _load_constants()).METADATA_FILENAME;
const folders = yield (_fs || _load_fs()).readdir(parentDir);
const packagesMetadata = [];
for (const folder of folders) {
if (folder[0] === '.') {
continue;
}
const loc = path.join(config.cacheFolder, parentDir.replace(config.cacheFolder, ''), folder);
// Check if this is a scoped package
if (!(yield (_fs || _load_fs()).exists(path.join(loc, metadataFile)))) {
// If so, recurrently read scoped packages metadata
packagesMetadata.push(...(yield readCacheMetadata(loc)));
} else {
var _ref2 = yield config.readPackageMetadata(loc);
const registry = _ref2.registry,
manifest = _ref2.package,
remote = _ref2.remote;
packagesMetadata.push([manifest.name, manifest.version, registry, remote && remote.resolved || '']);
}
}
return packagesMetadata;
});
return function readCacheMetadata() {
return _ref.apply(this, arguments);
};
})();
const body = yield readCacheMetadata();
reporter.table(['Name', 'Version', 'Registry', 'Resolved'], body);
})();
},
dir(config, reporter) {
reporter.log(config.cacheFolder);
},
clean(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (config.cacheFolder) {
yield (_fs || _load_fs()).unlink(config._cacheRootFolder);
yield (_fs || _load_fs()).mkdirp(config.cacheFolder);
reporter.success(reporter.lang('clearedCache'));
}
})();
}
});
const run = _buildSubCommands.run,
setFlags = _buildSubCommands.setFlags;
exports.run = run;
exports.setFlags = setFlags;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.verifyTreeCheck = exports.noArguments = exports.requireLockfile = undefined;
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let verifyTreeCheck = exports.verifyTreeCheck = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
let errCount = 0;
function reportError(msg) {
for (var _len = arguments.length, vars = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
vars[_key - 1] = arguments[_key];
}
reporter.error(reporter.lang(msg, ...vars));
errCount++;
}
// check all dependencies recursively without relying on internal resolver
const registryName = 'yarn';
const registry = config.registries[registryName];
const rootManifest = yield config.readManifest(registry.cwd, registryName);
const dependenciesToCheckVersion = [];
if (rootManifest.dependencies) {
for (const name in rootManifest.dependencies) {
dependenciesToCheckVersion.push({
name,
originalKey: name,
parentCwd: registry.cwd,
version: rootManifest.dependencies[name]
});
}
}
if (rootManifest.devDependencies && !config.production) {
for (const name in rootManifest.devDependencies) {
dependenciesToCheckVersion.push({
name,
originalKey: name,
parentCwd: registry.cwd,
version: rootManifest.devDependencies[name]
});
}
}
const locationsVisited = new Set();
while (dependenciesToCheckVersion.length) {
const dep = dependenciesToCheckVersion.shift();
const manifestLoc = path.join(dep.parentCwd, registry.folder, dep.name);
if (locationsVisited.has(manifestLoc + `@${dep.version}`)) {
continue;
}
locationsVisited.add(manifestLoc + `@${dep.version}`);
if (!(yield (_fs || _load_fs()).exists(manifestLoc))) {
reportError('packageNotInstalled', `${dep.originalKey}`);
continue;
}
const pkg = yield config.readManifest(manifestLoc, registryName);
if (semver.validRange(dep.version, config.looseSemver) && !semver.satisfies(pkg.version, dep.version, config.looseSemver)) {
reportError('packageWrongVersion', dep.originalKey, dep.version, pkg.version);
continue;
}
const dependencies = pkg.dependencies;
if (dependencies) {
for (const subdep in dependencies) {
const subDepPath = path.join(manifestLoc, registry.folder, subdep);
let found = false;
const relative = path.relative(registry.cwd, subDepPath);
const locations = path.normalize(relative).split(registry.folder + path.sep).filter(function (dir) {
return !!dir;
});
locations.pop();
while (locations.length >= 0) {
let possiblePath;
if (locations.length > 0) {
possiblePath = path.join(registry.cwd, registry.folder, locations.join(path.sep + registry.folder + path.sep));
} else {
possiblePath = registry.cwd;
}
if (yield (_fs || _load_fs()).exists(path.join(possiblePath, registry.folder, subdep))) {
dependenciesToCheckVersion.push({
name: subdep,
originalKey: `${dep.originalKey}#${subdep}`,
parentCwd: possiblePath,
version: dependencies[subdep]
});
found = true;
break;
}
if (!locations.length) {
break;
}
locations.pop();
}
if (!found) {
reportError('packageNotInstalled', `${dep.originalKey}#${subdep}`);
}
}
}
}
if (errCount > 0) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('foundErrors', errCount));
} else {
reporter.success(reporter.lang('folderInSync'));
}
});
return function verifyTreeCheck(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
let integrityHashCheck = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
let errCount = 0;
function reportError(msg) {
for (var _len2 = arguments.length, vars = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
vars[_key2 - 1] = arguments[_key2];
}
reporter.error(reporter.lang(msg, ...vars));
errCount++;
}
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd);
const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile);
// get patterns that are installed when running `yarn install`
var _ref3 = yield install.hydrate(true);
const rawPatterns = _ref3.patterns;
const patterns = yield install.flatten(rawPatterns);
// check if patterns exist in lockfile
for (const pattern of patterns) {
if (!lockfile.getLocked(pattern)) {
reportError('lockfileNotContainPatter', pattern);
}
}
const integrityLoc = yield install.getIntegrityHashLocation();
if (integrityLoc && (yield (_fs || _load_fs()).exists(integrityLoc))) {
const match = yield install.matchesIntegrityHash(patterns);
if (match.matches === false) {
reportError('integrityHashesDontMatch', match.expected, match.actual);
}
} else {
reportError('noIntegirtyHashFile');
}
if (errCount > 0) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('foundErrors', errCount));
} else {
reporter.success(reporter.lang('folderInSync'));
}
});
return function integrityHashCheck(_x5, _x6, _x7, _x8) {
return _ref2.apply(this, arguments);
};
})();
let run = exports.run = (() => {
var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
if (flags.verifyTree) {
yield verifyTreeCheck(config, reporter, flags, args);
return;
} else if (flags.integrity) {
yield integrityHashCheck(config, reporter, flags, args);
return;
}
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd);
const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile);
function humaniseLocation(loc) {
const relative = path.relative(path.join(config.cwd, 'node_modules'), loc);
const normalized = path.normalize(relative).split(path.sep);
return normalized.filter(p => p !== 'node_modules').reduce((result, part) => {
const length = result.length;
if (length && result[length - 1].startsWith('@') && !result[length - 1].includes(path.sep)) {
result[length - 1] += path.sep + part;
} else {
result.push(part);
}
return result;
}, []);
}
let warningCount = 0;
let errCount = 0;
function reportError(msg) {
for (var _len3 = arguments.length, vars = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
vars[_key3 - 1] = arguments[_key3];
}
reporter.error(reporter.lang(msg, ...vars));
errCount++;
}
// get patterns that are installed when running `yarn install`
var _ref5 = yield install.hydrate(true);
const rawPatterns = _ref5.patterns;
const patterns = yield install.flatten(rawPatterns);
// check if patterns exist in lockfile
for (const pattern of patterns) {
if (!lockfile.getLocked(pattern)) {
reportError('lockfileNotContainPatter', pattern);
}
}
// check if any of the node_modules are out of sync
const res = yield install.linker.getFlatHoistedTree(patterns);
for (const _ref6 of res) {
var _ref7 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref6, 2);
const loc = _ref7[0];
var _ref7$ = _ref7[1];
const originalKey = _ref7$.originalKey;
const pkg = _ref7$.pkg;
const ignore = _ref7$.ignore;
if (ignore) {
continue;
}
const parts = humaniseLocation(loc);
// grey out hoisted portions of key
let human = originalKey;
const hoistedParts = parts.slice();
const hoistedKey = parts.join('#');
if (human !== hoistedKey) {
const humanParts = human.split('#');
for (let i = 0; i < humanParts.length; i++) {
const humanPart = humanParts[i];
if (hoistedParts[0] === humanPart) {
hoistedParts.shift();
if (i < humanParts.length - 1) {
humanParts[i] += '#';
}
} else {
humanParts[i] = reporter.format.dim(`${humanPart}#`);
}
}
human = humanParts.join('');
}
const pkgLoc = path.join(loc, 'package.json');
if (!(yield (_fs || _load_fs()).exists(loc)) || !(yield (_fs || _load_fs()).exists(pkgLoc))) {
if (pkg._reference.optional) {
reporter.warn(reporter.lang('optionalDepNotInstalled', human));
} else {
reportError('packageNotInstalled', human);
}
continue;
}
const packageJson = yield config.readJson(pkgLoc);
if (pkg.version !== packageJson.version) {
// node_modules contains wrong version
reportError('packageWrongVersion', human, pkg.version, packageJson.version);
}
const deps = Object.assign({}, packageJson.dependencies, packageJson.peerDependencies);
for (const name in deps) {
const range = deps[name];
if (!semver.validRange(range, config.looseSemver)) {
continue; // exotic
}
const subHuman = `${human}#${name}@${range}`;
// find the package that this will resolve to, factoring in hoisting
const possibles = [];
let depPkgLoc;
for (let i = parts.length; i >= 0; i--) {
const myParts = parts.slice(0, i).concat(name);
// build package.json location for this position
const myDepPkgLoc = path.join(config.cwd, 'node_modules', myParts.join(`${path.sep}node_modules${path.sep}`), 'package.json');
possibles.push(myDepPkgLoc);
}
while (possibles.length) {
const myDepPkgLoc = possibles.shift();
if (yield (_fs || _load_fs()).exists(myDepPkgLoc)) {
depPkgLoc = myDepPkgLoc;
break;
}
}
if (!depPkgLoc) {
// we'll hit the module not install error above when this module is hit
continue;
}
//
const depPkg = yield config.readJson(depPkgLoc);
const foundHuman = `${humaniseLocation(path.dirname(depPkgLoc)).join('#')}@${depPkg.version}`;
if (!semver.satisfies(depPkg.version, range, config.looseSemver)) {
// module isn't correct semver
reportError('packageDontSatisfy', subHuman, foundHuman);
continue;
}
// check for modules above us that this could be deduped to
for (const loc of possibles) {
if (!(yield (_fs || _load_fs()).exists(loc))) {
continue;
}
const packageJson = yield config.readJson(loc);
if (packageJson.version === depPkg.version || semver.satisfies(packageJson.version, range, config.looseSemver) && semver.gt(packageJson.version, depPkg.version, config.looseSemver)) {
reporter.warn(reporter.lang('couldBeDeduped', subHuman, packageJson.version, `${humaniseLocation(path.dirname(loc)).join('#')}@${packageJson.version}`));
warningCount++;
}
break;
}
}
}
if (warningCount > 1) {
reporter.info(reporter.lang('foundWarnings', warningCount));
}
if (errCount > 0) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('foundErrors', errCount));
} else {
reporter.success(reporter.lang('folderInSync'));
}
});
return function run(_x9, _x10, _x11, _x12) {
return _ref4.apply(this, arguments);
};
})();
exports.setFlags = setFlags;
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _install;
function _load_install() {
return _install = require('./install.js');
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const semver = require('semver');
const path = require('path');
const requireLockfile = exports.requireLockfile = true;
const noArguments = exports.noArguments = true;
function setFlags(commander) {
commander.option('--integrity');
commander.option('--verify-tree');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.clean = exports.noArguments = exports.requireLockfile = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let clean = exports.clean = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter) {
const loc = path.join(config.cwd, (_constants || _load_constants()).CLEAN_FILENAME);
const file = yield (_fs || _load_fs()).readFile(loc);
const lines = file.split('\n');
const filters = (0, (_filter || _load_filter()).ignoreLinesToRegex)(lines);
let removedFiles = 0;
let removedSize = 0;
// build list of possible module folders
const locs = new Set();
if (config.modulesFolder) {
locs.add(config.modulesFolder);
}
for (const name of (_index || _load_index()).registryNames) {
const registry = config.registries[name];
locs.add(path.join(config.cwd, registry.folder));
}
for (const folder of locs) {
if (!(yield (_fs || _load_fs()).exists(folder))) {
continue;
}
const spinner = reporter.activity();
const files = yield (_fs || _load_fs()).walk(folder);
var _sortFilter = (0, (_filter || _load_filter()).sortFilter)(files, filters);
const ignoreFiles = _sortFilter.ignoreFiles;
spinner.end();
const tick = reporter.progress(ignoreFiles.size);
// TODO make sure `main` field of all modules isn't ignored
for (const file of ignoreFiles) {
const loc = path.join(folder, file);
const stat = yield (_fs || _load_fs()).lstat(loc);
removedSize += stat.size;
removedFiles++;
}
for (const file of ignoreFiles) {
const loc = path.join(folder, file);
yield (_fs || _load_fs()).unlink(loc);
tick();
}
}
return { removedFiles, removedSize };
});
return function clean(_x, _x2) {
return _ref.apply(this, arguments);
};
})();
let run = exports.run = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
reporter.step(1, 2, reporter.lang('cleanCreatingFile', (_constants || _load_constants()).CLEAN_FILENAME));
const cleanLoc = path.join(config.cwd, (_constants || _load_constants()).CLEAN_FILENAME);
if (!(yield (_fs || _load_fs()).exists(cleanLoc))) {
yield (_fs || _load_fs()).writeFile(cleanLoc, `${DEFAULT_FILTER}\n`, { flag: 'wx' });
}
reporter.step(2, 2, reporter.lang('cleaning'));
var _ref3 = yield clean(config, reporter);
const removedFiles = _ref3.removedFiles,
removedSize = _ref3.removedSize;
reporter.info(reporter.lang('cleanRemovedFiles', removedFiles));
reporter.info(reporter.lang('cleanSavedSize', Number((removedSize / 1024 / 1024).toFixed(2))));
});
return function run(_x3, _x4, _x5, _x6) {
return _ref2.apply(this, arguments);
};
})();
var _index;
function _load_index() {
return _index = require('../../registries/index.js');
}
var _filter;
function _load_filter() {
return _filter = require('../../util/filter.js');
}
var _constants;
function _load_constants() {
return _constants = require('../../constants.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
const requireLockfile = exports.requireLockfile = true;
const noArguments = exports.noArguments = true;
const DEFAULT_FILTER = `
# test directories
__tests__
test
tests
powered-test
# asset directories
docs
doc
website
images
assets
# examples
example
examples
# code coverage directories
coverage
.nyc_output
# build scripts
Makefile
Gulpfile.js
Gruntfile.js
# configs
.tern-project
.gitattributes
.editorconfig
.*ignore
.eslintrc
.jshintrc
.flowconfig
.documentup.json
.yarn-metadata.json
.*.yml
*.yml
# misc
*.gz
*.md
`.trim();
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setFlags = exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
exports.hasWrapper = hasWrapper;
var _buildSubCommands2;
function _load_buildSubCommands() {
return _buildSubCommands2 = _interopRequireDefault(require('./_build-sub-commands.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function hasWrapper(flags, args) {
return args[0] !== 'get';
}
/* eslint object-shorthand: 0 */
var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('config', {
set(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (args.length === 0 || args.length > 2) {
return false;
}
const key = args[0];
const val = args[1] || true;
const yarnConfig = config.registries.yarn;
yield yarnConfig.saveHomeConfig({ [key]: val });
reporter.success(reporter.lang('configSet', key, val));
return true;
})();
},
get(config, reporter, flags, args) {
if (args.length !== 1) {
return false;
}
reporter.log(String(config.getOption(args[0])));
return true;
},
delete: (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
if (args.length !== 1) {
return false;
}
const key = args[0];
const yarnConfig = config.registries.yarn;
yield yarnConfig.saveHomeConfig({ [key]: undefined });
reporter.success(reporter.lang('configDelete', key));
return true;
});
return function _delete(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})(),
list(config, reporter, flags, args) {
if (args.length) {
return false;
}
reporter.info(reporter.lang('configYarn'));
reporter.inspect(config.registries.yarn.config);
reporter.info(reporter.lang('configNpm'));
reporter.inspect(config.registries.npm.config);
return true;
}
});
const run = _buildSubCommands.run,
setFlags = _buildSubCommands.setFlags;
exports.run = run;
exports.setFlags = setFlags;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.examples = exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
let manifest;
if (flags.useManifest) {
manifest = yield config.readJson(flags.useManifest);
} else {
manifest = yield config.readRootManifest();
}
if (!manifest.name) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('noName'));
}
if (!manifest.version) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('noVersion'));
}
const entry = {
name: manifest.name,
version: manifest.version,
resolved: flags.resolved,
registry: flags.registry || manifest._registry,
optionalDependencies: manifest.optionalDependencies,
dependencies: manifest.dependencies
};
const pattern = flags.pattern || `${entry.name}@${entry.version}`;
console.log((0, (_stringify || _load_stringify()).default)({
[pattern]: (0, (_wrapper || _load_wrapper()).implodeEntry)(pattern, entry)
}));
});
return function run(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
exports.hasWrapper = hasWrapper;
exports.setFlags = setFlags;
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _wrapper;
function _load_wrapper() {
return _wrapper = require('../../lockfile/wrapper.js');
}
var _stringify;
function _load_stringify() {
return _stringify = _interopRequireDefault(require('../../lockfile/stringify.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function hasWrapper() {
return false;
}
function setFlags(commander) {
commander.option('--use-manifest <location>', 'description');
commander.option('--resolved <resolved>', 'description');
commander.option('--registry <registry>', 'description');
}
const examples = exports.examples = ['generate-lock-entry', 'generate-lock-entry --use-manifest ./package.json', 'generate-lock-entry --resolved local-file.tgz#hash'];
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let updateCwd = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) {
yield config.init({
cwd: config.globalFolder,
binLinks: true,
globalFolder: config.globalFolder,
cacheFolder: config._cacheRootFolder,
linkFolder: config.linkFolder
});
});
return function updateCwd(_x) {
return _ref.apply(this, arguments);
};
})();
let getBins = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) {
// build up list of registry folders to search for binaries
const dirs = [];
for (const registryName of Object.keys((_index || _load_index()).registries)) {
const registry = config.registries[registryName];
dirs.push(registry.loc);
}
// build up list of binary files
const paths = new Set();
for (const dir of dirs) {
const binDir = path.join(dir, '.bin');
if (!(yield (_fs || _load_fs()).exists(binDir))) {
continue;
}
for (const name of yield (_fs || _load_fs()).readdir(binDir)) {
paths.add(path.join(binDir, name));
}
}
return paths;
});
return function getBins(_x2) {
return _ref2.apply(this, arguments);
};
})();
let initUpdateBins = (() => {
var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags) {
const beforeBins = yield getBins(config);
const binFolder = getBinFolder(config, flags);
function throwPermError(err, dest) {
if (err.code === 'EACCES') {
throw new (_errors || _load_errors()).MessageError(reporter.lang('noFilePermission', dest));
} else {
throw err;
}
}
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const afterBins = yield getBins(config);
// remove old bins
for (const src of beforeBins) {
if (afterBins.has(src)) {
// not old
continue;
}
// remove old bin
const dest = path.join(binFolder, path.basename(src));
try {
yield (_fs || _load_fs()).unlink(dest);
} catch (err) {
throwPermError(err, dest);
}
}
// add new bins
for (const src of afterBins) {
if (beforeBins.has(src)) {
// already inserted
continue;
}
// insert new bin
const dest = path.join(binFolder, path.basename(src));
try {
yield (_fs || _load_fs()).unlink(dest);
yield (0, (_packageLinker || _load_packageLinker()).linkBin)(src, dest);
if (process.platform === 'win32' && dest.indexOf('.cmd') !== -1) {
yield (_fs || _load_fs()).rename(dest + '.cmd', dest);
}
} catch (err) {
throwPermError(err, dest);
}
}
});
});
return function initUpdateBins(_x3, _x4, _x5) {
return _ref3.apply(this, arguments);
};
})();
exports.hasWrapper = hasWrapper;
exports.getBinFolder = getBinFolder;
exports.setFlags = setFlags;
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _index;
function _load_index() {
return _index = require('../../registries/index.js');
}
var _baseReporter;
function _load_baseReporter() {
return _baseReporter = _interopRequireDefault(require('../../reporters/base-reporter.js'));
}
var _buildSubCommands2;
function _load_buildSubCommands() {
return _buildSubCommands2 = _interopRequireDefault(require('./_build-sub-commands.js'));
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _install;
function _load_install() {
return _install = require('./install.js');
}
var _add;
function _load_add() {
return _add = require('./add.js');
}
var _remove;
function _load_remove() {
return _remove = require('./remove.js');
}
var _upgrade;
function _load_upgrade() {
return _upgrade = require('./upgrade.js');
}
var _upgradeInteractive;
function _load_upgradeInteractive() {
return _upgradeInteractive = require('./upgrade-interactive.js');
}
var _packageLinker;
function _load_packageLinker() {
return _packageLinker = require('../../package-linker.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class GlobalAdd extends (_add || _load_add()).Add {
maybeOutputSaveTree() {
for (const pattern of this.addedPatterns) {
const manifest = this.resolver.getStrictResolvedPattern(pattern);
ls(manifest, this.reporter, true);
}
return Promise.resolve();
}
_logSuccessSaveLockfile() {
// noop
}
}
const path = require('path');
function hasWrapper(flags, args) {
return args[0] !== 'bin';
}
function getGlobalPrefix(config, flags) {
if (flags.prefix) {
return flags.prefix;
} else if (config.getOption('prefix')) {
return String(config.getOption('prefix'));
} else if (process.env.PREFIX) {
return process.env.PREFIX;
} else if (process.platform === 'win32') {
// c:\node\node.exe --> prefix=c:\node\
return path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
let prefix = path.dirname(path.dirname(process.execPath));
// destdir only is respected on Unix
if (process.env.DESTDIR) {
prefix = path.join(process.env.DESTDIR, prefix);
}
return prefix;
}
}
function getBinFolder(config, flags) {
const prefix = getGlobalPrefix(config, flags);
if (process.platform === 'win32') {
return prefix;
} else {
return path.resolve(prefix, 'bin');
}
}
function ls(manifest, reporter, saved) {
const bins = manifest.bin ? Object.keys(manifest.bin) : [];
const human = `${manifest.name}@${manifest.version}`;
if (bins.length) {
if (saved) {
reporter.success(reporter.lang('packageInstalledWithBinaries', human));
} else {
reporter.info(reporter.lang('packageHasBinaries', human));
}
reporter.list(`bins-${manifest.name}`, bins);
} else if (saved) {
reporter.warn(reporter.lang('packageHasNoBinaries'));
}
}
var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('global', {
add(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield updateCwd(config);
const updateBins = yield initUpdateBins(config, reporter, flags);
// install module
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd);
const install = new GlobalAdd(args, flags, config, reporter, lockfile);
yield install.init();
// link binaries
yield updateBins();
})();
},
bin(config, reporter, flags, args) {
console.log(getBinFolder(config, flags));
},
ls(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield updateCwd(config);
// install so we get hard file paths
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd);
const install = new (_install || _load_install()).Install({ skipIntegrity: true }, config, new (_baseReporter || _load_baseReporter()).default(), lockfile);
const patterns = yield install.init();
// dump global modules
for (const pattern of patterns) {
const manifest = install.resolver.getStrictResolvedPattern(pattern);
ls(manifest, reporter, false);
}
})();
},
remove(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield updateCwd(config);
const updateBins = yield initUpdateBins(config, reporter, flags);
// remove module
yield (0, (_remove || _load_remove()).run)(config, reporter, flags, args);
// remove binaries
yield updateBins();
})();
},
upgrade(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield updateCwd(config);
const updateBins = yield initUpdateBins(config, reporter, flags);
// upgrade module
yield (0, (_upgrade || _load_upgrade()).run)(config, reporter, flags, args);
// update binaries
yield updateBins();
})();
},
upgradeInteractive(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield updateCwd(config);
const updateBins = yield initUpdateBins(config, reporter, flags);
// upgrade module
yield (0, (_upgradeInteractive || _load_upgradeInteractive()).run)(config, reporter, flags, args);
// update binaries
yield updateBins();
})();
}
});
const run = _buildSubCommands.run,
_setFlags = _buildSubCommands.setFlags;
exports.run = run;
function setFlags(commander) {
_setFlags(commander);
commander.option('--prefix <prefix>', 'bin prefix to use to install binaries');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = run;
var _index;
function _load_index() {
return _index = _interopRequireWildcard(require('./index.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../../constants.js'));
}
var _misc;
function _load_misc() {
return _misc = require('../../util/misc.js');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
const chalk = require('chalk');
function run(config, reporter, commander, args) {
const getDocsLink = name => `${(_constants || _load_constants()).YARN_DOCS}${name || ''}`;
const getDocsInfo = name => 'Visit ' + chalk.bold(getDocsLink(name)) + ' for documentation about this command.';
if (args.length) {
const helpCommand = (0, (_misc || _load_misc()).hyphenate)(args[0]);
if ((_index || _load_index())[helpCommand]) {
commander.on('--help', () => console.log(' ' + getDocsInfo(helpCommand) + '\n'));
}
} else {
commander.on('--help', () => {
console.log(' Commands:\n');
for (const name of Object.keys(_index || _load_index()).sort((_misc || _load_misc()).sortAlpha)) {
if ((_index || _load_index())[name].useless) {
continue;
}
console.log(` - ${(0, (_misc || _load_misc()).hyphenate)(name)}`);
}
console.log('\n Run `' + chalk.bold('yarn help COMMAND') + '` for more information on specific commands.');
console.log(' Visit ' + chalk.bold(getDocsLink()) + ' to learn more about Yarn.\n');
});
}
commander.help();
return Promise.resolve();
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.Import = exports.noArguments = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
const imp = new Import(flags, config, reporter, new (_wrapper || _load_wrapper()).default({}));
yield imp.init();
});
return function run(_x, _x2, _x3, _x4) {
return _ref2.apply(this, arguments);
};
})();
var _install;
function _load_install() {
return _install = require('./install.js');
}
var _check;
function _load_check() {
return _check = require('./check.js');
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _baseResolver;
function _load_baseResolver() {
return _baseResolver = _interopRequireDefault(require('../../resolvers/base-resolver.js'));
}
var _hostedGitResolver;
function _load_hostedGitResolver() {
return _hostedGitResolver = _interopRequireDefault(require('../../resolvers/exotics/hosted-git-resolver.js'));
}
var _hostedGitResolver2;
function _load_hostedGitResolver2() {
return _hostedGitResolver2 = require('../../resolvers/exotics/hosted-git-resolver.js');
}
var _gistResolver;
function _load_gistResolver() {
return _gistResolver = _interopRequireDefault(require('../../resolvers/exotics/gist-resolver.js'));
}
var _gistResolver2;
function _load_gistResolver2() {
return _gistResolver2 = require('../../resolvers/exotics/gist-resolver.js');
}
var _gitResolver;
function _load_gitResolver() {
return _gitResolver = _interopRequireDefault(require('../../resolvers/exotics/git-resolver.js'));
}
var _fileResolver;
function _load_fileResolver() {
return _fileResolver = _interopRequireDefault(require('../../resolvers/exotics/file-resolver.js'));
}
var _packageResolver;
function _load_packageResolver() {
return _packageResolver = _interopRequireDefault(require('../../package-resolver.js'));
}
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('../../package-request.js'));
}
var _packageFetcher;
function _load_packageFetcher() {
return _packageFetcher = _interopRequireDefault(require('../../package-fetcher.js'));
}
var _packageLinker;
function _load_packageLinker() {
return _packageLinker = _interopRequireDefault(require('../../package-linker.js'));
}
var _packageCompatibility;
function _load_packageCompatibility() {
return _packageCompatibility = _interopRequireDefault(require('../../package-compatibility.js'));
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _misc;
function _load_misc() {
return _misc = _interopRequireWildcard(require('../../util/misc.js'));
}
var _constants;
function _load_constants() {
return _constants = require('../../constants.js');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const NPM_REGISTRY = /http[s]:\/\/registry.npmjs.org/g;
const invariant = require('invariant');
const path = require('path');
const noArguments = exports.noArguments = true;
class ImportResolver extends (_baseResolver || _load_baseResolver()).default {
getCwd() {
if (this.request.parentRequest) {
const parent = this.resolver.getStrictResolvedPattern(this.request.parentRequest.pattern);
invariant(parent._loc, 'expected package location');
return path.dirname(parent._loc);
}
return this.config.cwd;
}
resolveHostedGit(info, Resolver) {
var _PackageRequest$norma = (_packageRequest || _load_packageRequest()).default.normalizePattern(this.pattern);
const range = _PackageRequest$norma.range;
const exploded = (0, (_hostedGitResolver2 || _load_hostedGitResolver2()).explodeHostedGitFragment)(range, this.reporter);
const hash = info.gitHead;
invariant(hash, 'expected package gitHead');
const url = Resolver.getTarballUrl(exploded, hash);
info._uid = hash;
info._remote = {
resolved: url,
type: 'tarball',
registry: this.registry,
reference: url,
hash: null
};
return info;
}
resolveGist(info, Resolver) {
var _PackageRequest$norma2 = (_packageRequest || _load_packageRequest()).default.normalizePattern(this.pattern);
const range = _PackageRequest$norma2.range;
var _explodeGistFragment = (0, (_gistResolver2 || _load_gistResolver2()).explodeGistFragment)(range, this.reporter);
const id = _explodeGistFragment.id;
const hash = info.gitHead;
invariant(hash, 'expected package gitHead');
const url = `https://gist.github.com/${id}.git`;
info._uid = hash;
info._remote = {
resolved: `${url}#${hash}`,
type: 'git',
registry: this.registry,
reference: url,
hash
};
return info;
}
resolveGit(info, Resolver) {
const url = info._resolved;
const hash = info.gitHead;
invariant(url, 'expected package _resolved');
invariant(hash, 'expected package gitHead');
info._uid = hash;
info._remote = {
resolved: `${url}#${hash}`,
type: 'git',
registry: this.registry,
reference: url,
hash
};
return info;
}
resolveFile(info, Resolver) {
var _PackageRequest$norma3 = (_packageRequest || _load_packageRequest()).default.normalizePattern(this.pattern);
const range = _PackageRequest$norma3.range;
let loc = (_misc || _load_misc()).removePrefix(range, 'file:');
if (!path.isAbsolute(loc)) {
loc = path.join(this.config.cwd, loc);
}
info._uid = info.version;
info._remote = {
type: 'copy',
registry: this.registry,
hash: null,
reference: loc
};
return info;
}
resolveRegistry(info) {
let url = info._resolved;
const hash = info._shasum;
invariant(url, 'expected package _resolved');
invariant(hash, 'expected package _shasum');
if (this.config.getOption('registry') === (_constants || _load_constants()).YARN_REGISTRY) {
url = url.replace(NPM_REGISTRY, (_constants || _load_constants()).YARN_REGISTRY);
}
info._uid = info.version;
info._remote = {
resolved: `${url}#${hash}`,
type: 'tarball',
registry: this.registry,
reference: url,
hash
};
return info;
}
resolveImport(info) {
var _PackageRequest$norma4 = (_packageRequest || _load_packageRequest()).default.normalizePattern(this.pattern);
const range = _PackageRequest$norma4.range;
const Resolver = (_packageRequest || _load_packageRequest()).default.getExoticResolver(range);
if (Resolver && Resolver.prototype instanceof (_hostedGitResolver || _load_hostedGitResolver()).default) {
return this.resolveHostedGit(info, Resolver);
} else if (Resolver && Resolver === (_gistResolver || _load_gistResolver()).default) {
return this.resolveGist(info, Resolver);
} else if (Resolver && Resolver === (_gitResolver || _load_gitResolver()).default) {
return this.resolveGit(info, Resolver);
} else if (Resolver && Resolver === (_fileResolver || _load_fileResolver()).default) {
return this.resolveFile(info, Resolver);
}
return this.resolveRegistry(info);
}
resolveLocation(loc) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const info = yield _this.config.tryManifest(loc, 'npm', false);
if (!info) {
return null;
}
return _this.resolveImport(info);
})();
}
resolve() {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
var _PackageRequest$norma5 = (_packageRequest || _load_packageRequest()).default.normalizePattern(_this2.pattern);
const name = _PackageRequest$norma5.name;
let cwd = _this2.getCwd();
while (!path.relative(_this2.config.cwd, cwd).startsWith('..')) {
const loc = path.join(cwd, 'node_modules', name);
const info = yield _this2.config.getCache(`import-resolver-${loc}`, function () {
return _this2.resolveLocation(loc);
});
if (info) {
return info;
}
cwd = path.resolve(cwd, '../..');
}
throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('importResolveFailed', name, _this2.getCwd()));
})();
}
}
class ImportPackageRequest extends (_packageRequest || _load_packageRequest()).default {
constructor(req, resolver) {
super(req, resolver);
this.import = this.parentRequest instanceof ImportPackageRequest ? this.parentRequest.import : true;
}
getRootName() {
return this.resolver instanceof ImportPackageResolver && this.resolver.rootName || 'root';
}
getParentHumanName() {
return [this.getRootName()].concat(this.getParentNames()).join(' > ');
}
reportResolvedRangeMatch(info, resolved) {
if (info.version === resolved.version) {
return;
}
this.reporter.warn(this.reporter.lang('importResolvedRangeMatch', resolved.version, resolved.name, info.version, this.getParentHumanName()));
}
findVersionInfo() {
if (!this.import) {
this.reporter.verbose(this.reporter.lang('skippingImport', this.pattern, this.getParentHumanName()));
return super.findVersionInfo();
}
const resolver = new ImportResolver(this, this.pattern);
return resolver.resolve().catch(() => {
this.import = false;
this.reporter.warn(this.reporter.lang('importFailed', this.pattern, this.getParentHumanName()));
return super.findVersionInfo();
});
}
}
class ImportPackageResolver extends (_packageResolver || _load_packageResolver()).default {
constructor(config, lockfile) {
super(config, lockfile);
this.next = [];
this.rootName = 'root';
}
find(req) {
this.next.push(req);
return Promise.resolve();
}
findOne(req) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (_this3.activity) {
_this3.activity.tick(req.pattern);
}
const request = new ImportPackageRequest(req, _this3);
yield request.find();
})();
}
findAll(deps) {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield Promise.all(deps.map(function (dep) {
return _this4.findOne(dep);
}));
deps = _this4.next;
_this4.next = [];
if (!deps.length) {
return;
}
yield _this4.findAll(deps);
})();
}
resetOptional() {
for (const pattern in this.patterns) {
const ref = this.patterns[pattern]._reference;
invariant(ref, 'expected reference');
ref.optional = null;
for (const req of ref.requests) {
ref.addOptional(req.optional);
}
}
}
init(deps, isFlat, rootName) {
var _this5 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this5.flat = isFlat;
_this5.rootName = rootName || _this5.rootName;
const activity = _this5.activity = _this5.reporter.activity();
_this5.seedPatterns = deps.map(function (dep) {
return dep.pattern;
});
yield _this5.findAll(deps);
_this5.resetOptional();
activity.end();
_this5.activity = null;
})();
}
}
class Import extends (_install || _load_install()).Install {
constructor(flags, config, reporter, lockfile) {
super(flags, config, reporter, lockfile);
this.resolver = new ImportPackageResolver(this.config, this.lockfile);
this.fetcher = new (_packageFetcher || _load_packageFetcher()).default(config, this.resolver);
this.compatibility = new (_packageCompatibility || _load_packageCompatibility()).default(config, this.resolver, this.flags.ignoreEngines);
this.linker = new (_packageLinker || _load_packageLinker()).default(config, this.resolver);
}
init() {
var _this6 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (yield (_fs || _load_fs()).exists(path.join(_this6.config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME))) {
throw new (_errors || _load_errors()).MessageError(_this6.reporter.lang('lockfileExists'));
}
yield (0, (_check || _load_check()).verifyTreeCheck)(_this6.config, _this6.reporter, {}, []);
var _ref = yield _this6.fetchRequestFromCwd();
const requests = _ref.requests,
patterns = _ref.patterns,
manifest = _ref.manifest;
yield _this6.resolver.init(requests, _this6.flags.flat, manifest.name);
yield _this6.fetcher.init();
yield _this6.compatibility.init();
yield _this6.linker.resolvePeerModules();
yield _this6.saveLockfileAndIntegrity(patterns);
return patterns;
})();
}
}
exports.Import = Import;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 33 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.prune = exports.dedupe = exports.lockfile = exports.upgradeInteractive = exports.why = exports.versions = exports.version = exports.upgrade = exports.unlink = exports.team = exports.tag = exports.run = exports.remove = exports.publish = exports.pack = exports.owner = exports.outdated = exports.list = exports.logout = exports.login = exports.link = exports.licenses = exports.install = exports.init = exports.info = exports.import = exports.help = exports.global = exports.generateLockEntry = exports.config = exports.clean = exports.check = exports.cache = exports.bin = exports.add = exports.access = undefined;
var _access;
function _load_access() {
return _access = _interopRequireWildcard(require('./access.js'));
}
var _add;
function _load_add() {
return _add = _interopRequireWildcard(require('./add.js'));
}
var _bin;
function _load_bin() {
return _bin = _interopRequireWildcard(require('./bin.js'));
}
var _cache;
function _load_cache() {
return _cache = _interopRequireWildcard(require('./cache.js'));
}
var _check;
function _load_check() {
return _check = _interopRequireWildcard(require('./check.js'));
}
var _clean;
function _load_clean() {
return _clean = _interopRequireWildcard(require('./clean.js'));
}
var _config;
function _load_config() {
return _config = _interopRequireWildcard(require('./config.js'));
}
var _generateLockEntry;
function _load_generateLockEntry() {
return _generateLockEntry = _interopRequireWildcard(require('./generate-lock-entry.js'));
}
var _global;
function _load_global() {
return _global = _interopRequireWildcard(require('./global.js'));
}
var _help;
function _load_help() {
return _help = _interopRequireWildcard(require('./help.js'));
}
var _import;
function _load_import() {
return _import = _interopRequireWildcard(require('./import.js'));
}
var _info;
function _load_info() {
return _info = _interopRequireWildcard(require('./info.js'));
}
var _init;
function _load_init() {
return _init = _interopRequireWildcard(require('./init.js'));
}
var _install;
function _load_install() {
return _install = _interopRequireWildcard(require('./install.js'));
}
var _licenses;
function _load_licenses() {
return _licenses = _interopRequireWildcard(require('./licenses.js'));
}
var _link;
function _load_link() {
return _link = _interopRequireWildcard(require('./link.js'));
}
var _login;
function _load_login() {
return _login = _interopRequireWildcard(require('./login.js'));
}
var _logout;
function _load_logout() {
return _logout = _interopRequireWildcard(require('./logout.js'));
}
var _list;
function _load_list() {
return _list = _interopRequireWildcard(require('./list.js'));
}
var _outdated;
function _load_outdated() {
return _outdated = _interopRequireWildcard(require('./outdated.js'));
}
var _owner;
function _load_owner() {
return _owner = _interopRequireWildcard(require('./owner.js'));
}
var _pack;
function _load_pack() {
return _pack = _interopRequireWildcard(require('./pack.js'));
}
var _publish;
function _load_publish() {
return _publish = _interopRequireWildcard(require('./publish.js'));
}
var _remove;
function _load_remove() {
return _remove = _interopRequireWildcard(require('./remove.js'));
}
var _run;
function _load_run() {
return _run = _interopRequireWildcard(require('./run.js'));
}
var _tag;
function _load_tag() {
return _tag = _interopRequireWildcard(require('./tag.js'));
}
var _team;
function _load_team() {
return _team = _interopRequireWildcard(require('./team.js'));
}
var _unlink;
function _load_unlink() {
return _unlink = _interopRequireWildcard(require('./unlink.js'));
}
var _upgrade;
function _load_upgrade() {
return _upgrade = _interopRequireWildcard(require('./upgrade.js'));
}
var _version;
function _load_version() {
return _version = _interopRequireWildcard(require('./version.js'));
}
var _versions;
function _load_versions() {
return _versions = _interopRequireWildcard(require('./versions.js'));
}
var _why;
function _load_why() {
return _why = _interopRequireWildcard(require('./why.js'));
}
var _upgradeInteractive;
function _load_upgradeInteractive() {
return _upgradeInteractive = _interopRequireWildcard(require('./upgrade-interactive.js'));
}
var _useless;
function _load_useless() {
return _useless = _interopRequireDefault(require('./_useless.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
exports.access = _access || _load_access();
exports.add = _add || _load_add();
exports.bin = _bin || _load_bin();
exports.cache = _cache || _load_cache();
exports.check = _check || _load_check();
exports.clean = _clean || _load_clean();
exports.config = _config || _load_config();
exports.generateLockEntry = _generateLockEntry || _load_generateLockEntry();
exports.global = _global || _load_global();
exports.help = _help || _load_help();
exports.import = _import || _load_import();
exports.info = _info || _load_info();
exports.init = _init || _load_init();
exports.install = _install || _load_install();
exports.licenses = _licenses || _load_licenses();
exports.link = _link || _load_link();
exports.login = _login || _load_login();
exports.logout = _logout || _load_logout();
exports.list = _list || _load_list();
exports.outdated = _outdated || _load_outdated();
exports.owner = _owner || _load_owner();
exports.pack = _pack || _load_pack();
exports.publish = _publish || _load_publish();
exports.remove = _remove || _load_remove();
exports.run = _run || _load_run();
exports.tag = _tag || _load_tag();
exports.team = _team || _load_team();
exports.unlink = _unlink || _load_unlink();
exports.upgrade = _upgrade || _load_upgrade();
exports.version = _version || _load_version();
exports.versions = _versions || _load_versions();
exports.why = _why || _load_why();
exports.upgradeInteractive = _upgradeInteractive || _load_upgradeInteractive();
const lockfile = exports.lockfile = (0, (_useless || _load_useless()).default)("The lockfile command isn't necessary. `yarn install` will produce a lockfile.");
const dedupe = exports.dedupe = (0, (_useless || _load_useless()).default)("The dedupe command isn't necessary. `yarn install` will already dedupe.");
const prune = exports.prune = (0, (_useless || _load_useless()).default)("The prune command isn't necessary. `yarn install` will prune extraneous packages.");
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
if (args.length > 2) {
reporter.error(reporter.lang('tooManyArguments', 2));
return;
}
let packageName = args.shift() || '.';
// Handle the case when we are referencing a local package.
if (packageName === '.') {
packageName = (yield config.readRootManifest()).name;
}
const packageInput = (_npmRegistry || _load_npmRegistry()).default.escapeName(packageName);
var _parsePackageName = (0, (_parsePackageName2 || _load_parsePackageName()).default)(packageInput);
const name = _parsePackageName.name,
version = _parsePackageName.version;
let result = yield config.registries.npm.request(name);
if (!result) {
reporter.error(reporter.lang('infoFail'));
return;
}
result = clean(result);
const versions = result.versions;
// $FlowFixMe
result.versions = Object.keys(versions).sort(semver.compareLoose);
result.version = version || result.versions[result.versions.length - 1];
result = Object.assign(result, versions[result.version]);
const fieldPath = args.shift();
const fields = fieldPath ? fieldPath.split('.') : [];
// Readmes can be long so exclude them unless explicitly asked for.
if (fields[0] !== 'readme') {
delete result.readme;
}
result = fields.reduce(function (prev, cur) {
return prev && prev[cur];
}, result);
reporter.inspect(result);
});
return function run(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
var _npmRegistry;
function _load_npmRegistry() {
return _npmRegistry = _interopRequireDefault(require('../../registries/npm-registry.js'));
}
var _parsePackageName2;
function _load_parsePackageName() {
return _parsePackageName2 = _interopRequireDefault(require('../../util/parse-package-name.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const semver = require('semver');
function clean(object) {
if (Array.isArray(object)) {
const result = [];
object.forEach(item => {
item = clean(item);
if (item) {
result.push(item);
}
});
return result;
} else if (typeof object === 'object') {
const result = {};
for (const key in object) {
if (key.startsWith('_')) {
continue;
}
const item = clean(object[key]);
if (item) {
result[key] = item;
}
}
return result;
} else if (object) {
return object;
} else {
return null;
}
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getGitConfigInfo = exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
const manifests = yield config.getRootManifests();
let repository = {};
const author = {
name: config.getOption('init-author-name'),
email: config.getOption('init-author-email'),
url: config.getOption('init-author-url')
};
if (yield (_fs || _load_fs()).exists(path.join(config.cwd, '.git'))) {
// get git origin of the cwd
try {
repository = {
type: 'git',
url: yield (_child || _load_child()).spawn('git', ['config', 'remote.origin.url'], { cwd: config.cwd })
};
} catch (ex) {
// Ignore - Git repo may not have an origin URL yet (eg. if it only exists locally)
}
if (author.name === undefined) {
author.name = yield getGitConfigInfo('user.name');
}
if (author.email === undefined) {
author.email = yield getGitConfigInfo('user.email');
}
}
const keys = [{
key: 'name',
question: 'name',
default: path.basename(config.cwd),
validation: (_validate || _load_validate()).isValidPackageName,
validationError: 'invalidPackageName'
}, {
key: 'version',
question: 'version',
default: String(config.getOption('init-version'))
}, {
key: 'description',
question: 'description',
default: ''
}, {
key: 'main',
question: 'entry point',
default: 'index.js'
}, {
key: 'repository',
question: 'repository url',
default: (0, (_util || _load_util()).extractRepositoryUrl)(repository)
}, {
key: 'author',
question: 'author',
default: (0, (_util || _load_util()).stringifyPerson)(author)
}, {
key: 'license',
question: 'license',
default: String(config.getOption('init-license'))
}];
// get answers
const pkg = {};
for (const entry of keys) {
const yes = flags.yes;
const manifestKey = entry.key;
let question = entry.question,
def = entry.default;
for (const registryName of (_index || _load_index()).registryNames) {
const object = manifests[registryName].object;
let val = objectPath.get(object, manifestKey);
if (!val) {
break;
}
if (typeof val === 'object') {
if (manifestKey === 'author') {
val = (0, (_util || _load_util()).stringifyPerson)(val);
} else if (manifestKey === 'repository') {
val = (0, (_util || _load_util()).extractRepositoryUrl)(val);
}
}
def = val;
}
if (def) {
question += ` (${def})`;
}
let answer;
let validAnswer = false;
if (yes) {
answer = def;
} else {
// loop until a valid answer is provided, if validation is on entry
if (entry.validation) {
while (!validAnswer) {
answer = (yield reporter.question(question)) || def;
// validate answer
if (entry.validation(String(answer))) {
validAnswer = true;
} else {
reporter.error(reporter.lang('invalidPackageName'));
}
}
} else {
answer = (yield reporter.question(question)) || def;
}
}
if (answer) {
objectPath.set(pkg, manifestKey, answer);
}
}
// save answers
const targetManifests = [];
for (const registryName of (_index || _load_index()).registryNames) {
const info = manifests[registryName];
if (info.exists) {
targetManifests.push(info);
}
}
if (!targetManifests.length) {
targetManifests.push(manifests.npm);
}
for (const targetManifest of targetManifests) {
Object.assign(targetManifest.object, pkg);
reporter.success(`Saved ${path.basename(targetManifest.loc)}`);
}
yield config.saveRootManifests(manifests);
});
return function run(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
let getGitConfigInfo = exports.getGitConfigInfo = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (credential) {
let spawn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_child || _load_child()).spawn;
try {
// try to get author default based on git config
return yield spawn('git', ['config', credential]);
} catch (e) {
return '';
}
});
return function getGitConfigInfo(_x5) {
return _ref2.apply(this, arguments);
};
})();
exports.setFlags = setFlags;
var _util;
function _load_util() {
return _util = require('../../util/normalize-manifest/util.js');
}
var _index;
function _load_index() {
return _index = require('../../registries/index.js');
}
var _child;
function _load_child() {
return _child = _interopRequireWildcard(require('../../util/child.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _validate;
function _load_validate() {
return _validate = _interopRequireWildcard(require('../../util/normalize-manifest/validate.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const objectPath = require('object-path');
const path = require('path');
function setFlags(commander) {
commander.option('-y, --yes', 'use default options');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 3 3 3 3 3 3 3 3 3 3 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 3 3 3 3 3 3 3 6 6 3 6 3 3 6 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.wrapLifecycle = exports.run = exports.Install = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
let lockfile;
Iif (flags.lockfile === false) {
lockfile = new (_wrapper || _load_wrapper()).default();
} else {
lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd, reporter);
}
Iif (args.length) {
const exampleArgs = args.slice();
if (flags.saveDev) {
exampleArgs.push('--dev');
}
if (flags.savePeer) {
exampleArgs.push('--peer');
}
if (flags.saveOptional) {
exampleArgs.push('--optional');
}
if (flags.saveExact) {
exampleArgs.push('--exact');
}
if (flags.saveTilde) {
exampleArgs.push('--tilde');
}
let command = 'add';
if (flags.global) {
command = 'global add';
}
throw new (_errors || _load_errors()).MessageError(reporter.lang('installCommandRenamed', `yarn ${command} ${exampleArgs.join(' ')}`));
}
yield wrapLifecycle(config, flags, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const install = new Install(flags, config, reporter, lockfile);
yield install.init();
}));
});
return function run(_x14, _x15, _x16, _x17) {
return _ref9.apply(this, arguments);
};
})();
let wrapLifecycle = exports.wrapLifecycle = (() => {
var _ref11 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags, factory) {
yield config.executeLifecycleScript('preinstall');
yield factory();
// npm behaviour, seems kinda funky but yay compatibility
yield config.executeLifecycleScript('install');
yield config.executeLifecycleScript('postinstall');
Eif (!config.production) {
yield config.executeLifecycleScript('prepublish');
}
});
return function wrapLifecycle(_x18, _x19, _x20) {
return _ref11.apply(this, arguments);
};
})();
exports.setFlags = setFlags;
var _index;
function _load_index() {
return _index = _interopRequireDefault(require('../../util/normalize-manifest/index.js'));
}
var _index2;
function _load_index2() {
return _index2 = require('../../registries/index.js');
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _stringify;
function _load_stringify() {
return _stringify = _interopRequireDefault(require('../../lockfile/stringify.js'));
}
var _packageFetcher;
function _load_packageFetcher() {
return _packageFetcher = _interopRequireDefault(require('../../package-fetcher.js'));
}
var _packageInstallScripts;
function _load_packageInstallScripts() {
return _packageInstallScripts = _interopRequireDefault(require('../../package-install-scripts.js'));
}
var _packageCompatibility;
function _load_packageCompatibility() {
return _packageCompatibility = _interopRequireDefault(require('../../package-compatibility.js'));
}
var _packageResolver;
function _load_packageResolver() {
return _packageResolver = _interopRequireDefault(require('../../package-resolver.js'));
}
var _packageLinker;
function _load_packageLinker() {
return _packageLinker = _interopRequireDefault(require('../../package-linker.js'));
}
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('../../package-request.js'));
}
var _clean;
function _load_clean() {
return _clean = require('./clean.js');
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../../constants.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _crypto;
function _load_crypto() {
return _crypto = _interopRequireWildcard(require('../../util/crypto.js'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('../../util/map.js'));
}
var _misc;
function _load_misc() {
return _misc = require('../../util/misc.js');
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const semver = require('semver');
const emoji = require('node-emoji');
const isCI = require('is-ci');
const path = require('path');
var _require = require('../../../package.json');
const YARN_VERSION = _require.version,
YARN_INSTALL_METHOD = _require.installationMethod;
const ONE_DAY = 1000 * 60 * 60 * 24;
/**
* Try and detect the installation method for Yarn and provide a command to update it with.
*/
function getUpdateCommand() {
if (YARN_INSTALL_METHOD === 'tar') {
return `curl -o- -L ${(_constants || _load_constants()).YARN_INSTALLER_SH} | bash`;
}
if (YARN_INSTALL_METHOD === 'homebrew') {
return 'brew upgrade yarn';
}
if (YARN_INSTALL_METHOD === 'deb') {
return 'sudo apt-get update && sudo apt-get install yarn';
}
if (YARN_INSTALL_METHOD === 'rpm') {
return 'sudo yum install yarn';
}
if (YARN_INSTALL_METHOD === 'npm') {
return 'npm upgrade --global yarn';
}
if (YARN_INSTALL_METHOD === 'chocolatey') {
return 'choco upgrade yarn';
}
if (YARN_INSTALL_METHOD === 'apk') {
return 'apk update && apk add -u yarn';
}
return null;
}
function getUpdateInstaller() {
// Windows
if (YARN_INSTALL_METHOD === 'msi') {
return (_constants || _load_constants()).YARN_INSTALLER_MSI;
}
return null;
}
function normalizeFlags(config, rawFlags) {
const flags = {
// install
har: !!rawFlags.har,
ignorePlatform: !!rawFlags.ignorePlatform,
ignoreEngines: !!rawFlags.ignoreEngines,
ignoreScripts: !!rawFlags.ignoreScripts,
ignoreOptional: !!rawFlags.ignoreOptional,
force: !!rawFlags.force,
flat: !!rawFlags.flat,
lockfile: rawFlags.lockfile !== false,
pureLockfile: !!rawFlags.pureLockfile,
skipIntegrityCheck: !!rawFlags.skipIntegrityCheck,
frozenLockfile: !!rawFlags.frozenLockfile,
linkDuplicates: !!rawFlags.linkDuplicates,
// add
peer: !!rawFlags.peer,
dev: !!rawFlags.dev,
optional: !!rawFlags.optional,
exact: !!rawFlags.exact,
tilde: !!rawFlags.tilde
};
Iif (config.getOption('ignore-scripts')) {
flags.ignoreScripts = true;
}
Iif (config.getOption('ignore-platform')) {
flags.ignorePlatform = true;
}
Iif (config.getOption('ignore-engines')) {
flags.ignoreEngines = true;
}
Iif (config.getOption('ignore-optional')) {
flags.ignoreOptional = true;
}
Iif (config.getOption('force')) {
flags.force = true;
}
return flags;
}
class Install {
constructor(flags, config, reporter, lockfile) {
this.rootManifestRegistries = [];
this.rootPatternsToOrigin = (0, (_map || _load_map()).default)();
this.resolutions = (0, (_map || _load_map()).default)();
this.lockfile = lockfile;
this.reporter = reporter;
this.config = config;
this.flags = normalizeFlags(config, flags);
this.resolver = new (_packageResolver || _load_packageResolver()).default(config, lockfile);
this.fetcher = new (_packageFetcher || _load_packageFetcher()).default(config, this.resolver);
this.compatibility = new (_packageCompatibility || _load_packageCompatibility()).default(config, this.resolver, this.flags.ignoreEngines);
this.linker = new (_packageLinker || _load_packageLinker()).default(config, this.resolver);
this.scripts = new (_packageInstallScripts || _load_packageInstallScripts()).default(config, this.resolver, this.flags.force);
}
/**
* Create a list of dependency requests from the current directories manifests.
*/
fetchRequestFromCwd() {
var _this = this;
let excludePatterns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const patterns = [];
const deps = [];
const manifest = {};
const ignorePatterns = [];
const usedPatterns = [];
// exclude package names that are in install args
const excludeNames = [];
for (const pattern of excludePatterns) {
// can't extract a package name from this
if ((_packageRequest || _load_packageRequest()).default.getExoticResolver(pattern)) {
continue;
}
// extract the name
const parts = (_packageRequest || _load_packageRequest()).default.normalizePattern(pattern);
excludeNames.push(parts.name);
}
for (const registry of Object.keys((_index2 || _load_index2()).registries)) {
const filename = (_index2 || _load_index2()).registries[registry].filename;
const loc = path.join(_this.config.cwd, filename);
Iif (!(yield (_fs || _load_fs()).exists(loc))) {
continue;
}
_this.rootManifestRegistries.push(registry);
const json = yield _this.config.readJson(loc);
yield (0, (_index || _load_index()).default)(json, _this.config.cwd, _this.config, true);
Object.assign(_this.resolutions, json.resolutions);
Object.assign(manifest, json);
const pushDeps = function (depType, _ref, isUsed) {
let hint = _ref.hint,
optional = _ref.optional;
const depMap = json[depType];
for (const name in depMap) {
Iif (excludeNames.indexOf(name) >= 0) {
continue;
}
let pattern = name;
Eif (!_this.lockfile.getLocked(pattern, true)) {
// when we use --save we save the dependency to the lockfile with just the name rather than the
// version combo
pattern += '@' + depMap[name];
}
Eif (isUsed) {
usedPatterns.push(pattern);
} else {
ignorePatterns.push(pattern);
}
_this.rootPatternsToOrigin[pattern] = depType;
patterns.push(pattern);
deps.push({ pattern, registry, hint, optional });
}
};
pushDeps('dependencies', { hint: null, optional: false }, true);
pushDeps('devDependencies', { hint: 'dev', optional: false }, !_this.config.production);
pushDeps('optionalDependencies', { hint: 'optional', optional: true }, !_this.flags.ignoreOptional);
break;
}
// inherit root flat flag
Iif (manifest.flat) {
_this.flags.flat = true;
}
return {
requests: deps,
patterns,
manifest,
usedPatterns,
ignorePatterns
};
})();
}
/**
* TODO description
*/
prepareRequests(requests) {
return requests;
}
preparePatterns(patterns) {
return patterns;
}
bailout(patterns) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
Iif (_this2.flags.frozenLockfile && !_this2.lockFileInSync(patterns)) {
throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('frozenLockfileError'));
}
Iif (_this2.flags.skipIntegrityCheck || _this2.flags.force) {
return false;
}
const match = yield _this2.matchesIntegrityHash(patterns);
const haveLockfile = yield (_fs || _load_fs()).exists(path.join(_this2.config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME));
Iif (match.matches && haveLockfile) {
_this2.reporter.success(_this2.reporter.lang('upToDate'));
return true;
}
Iif (!patterns.length && !match.expected) {
_this2.reporter.success(_this2.reporter.lang('nothingToInstall'));
yield _this2.createEmptyManifestFolders();
yield _this2.saveLockfileAndIntegrity(patterns);
return true;
}
return false;
})();
}
/**
* Produce empty folders for all used root manifests.
*/
createEmptyManifestFolders() {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (_this3.config.modulesFolder) {
// already created
return;
}
for (const registryName of _this3.rootManifestRegistries) {
const folder = _this3.config.registries[registryName].folder;
yield (_fs || _load_fs()).mkdirp(path.join(_this3.config.cwd, folder));
}
})();
}
/**
* TODO description
*/
markIgnored(patterns) {
for (const pattern of patterns) {
const manifest = this.resolver.getStrictResolvedPattern(pattern);
const ref = manifest._reference;
invariant(ref, 'expected package reference');
if (ref.requests.length === 1) {
// this module was only depended on once by the root so we can safely ignore it
// if it was requested more than once then ignoring it would break a transitive
// dep that resolved to it
ref.ignore = true;
}
}
}
/**
* TODO description
*/
init() {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this4.checkUpdate();
// warn if we have a shrinkwrap
Iif (yield (_fs || _load_fs()).exists(path.join(_this4.config.cwd, 'npm-shrinkwrap.json'))) {
_this4.reporter.warn(_this4.reporter.lang('shrinkwrapWarning'));
}
let patterns = [];
const steps = [];
var _ref2 = yield _this4.fetchRequestFromCwd();
const depRequests = _ref2.requests,
rawPatterns = _ref2.patterns,
ignorePatterns = _ref2.ignorePatterns,
usedPatterns = _ref2.usedPatterns;
steps.push((() => {
var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) {
_this4.reporter.step(curr, total, _this4.reporter.lang('resolvingPackages'), emoji.get('mag'));
yield _this4.resolver.init(_this4.prepareRequests(depRequests), _this4.flags.flat);
patterns = yield _this4.flatten(_this4.preparePatterns(rawPatterns));
return { bailout: yield _this4.bailout(usedPatterns) };
});
return function (_x2, _x3) {
return _ref3.apply(this, arguments);
};
})());
steps.push((() => {
var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) {
_this4.markIgnored(ignorePatterns);
_this4.reporter.step(curr, total, _this4.reporter.lang('fetchingPackages'), emoji.get('truck'));
yield _this4.fetcher.init();
yield _this4.compatibility.init();
});
return function (_x4, _x5) {
return _ref4.apply(this, arguments);
};
})());
steps.push((() => {
var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) {
// remove integrity hash to make this operation atomic
const loc = yield _this4.getIntegrityHashLocation();
yield (_fs || _load_fs()).unlink(loc);
_this4.reporter.step(curr, total, _this4.reporter.lang('linkingDependencies'), emoji.get('link'));
yield _this4.linker.init(patterns, _this4.flags.linkDuplicates);
});
return function (_x6, _x7) {
return _ref5.apply(this, arguments);
};
})());
steps.push((() => {
var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) {
_this4.reporter.step(curr, total, _this4.flags.force ? _this4.reporter.lang('rebuildingPackages') : _this4.reporter.lang('buildingFreshPackages'), emoji.get('page_with_curl'));
Iif (_this4.flags.ignoreScripts) {
_this4.reporter.warn(_this4.reporter.lang('ignoredScripts'));
} else {
yield _this4.scripts.init(patterns);
}
});
return function (_x8, _x9) {
return _ref6.apply(this, arguments);
};
})());
Iif (_this4.flags.har) {
steps.push((() => {
var _ref7 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) {
const formattedDate = new Date().toISOString().replace(/:/g, '-');
const filename = `yarn-install_${formattedDate}.har`;
_this4.reporter.step(curr, total, _this4.reporter.lang('savingHar', filename), emoji.get('black_circle_for_record'));
yield _this4.config.requestManager.saveHar(filename);
});
return function (_x10, _x11) {
return _ref7.apply(this, arguments);
};
})());
}
Iif (yield _this4.shouldClean()) {
steps.push((() => {
var _ref8 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) {
_this4.reporter.step(curr, total, _this4.reporter.lang('cleaningModules'), emoji.get('recycle'));
yield (0, (_clean || _load_clean()).clean)(_this4.config, _this4.reporter);
});
return function (_x12, _x13) {
return _ref8.apply(this, arguments);
};
})());
}
let currentStep = 0;
for (const step of steps) {
const stepResult = yield step(++currentStep, steps.length);
Iif (stepResult && stepResult.bailout) {
return patterns;
}
}
// fin!
yield _this4.saveLockfileAndIntegrity(patterns);
_this4.maybeOutputUpdate();
_this4.config.requestManager.clearCache();
return patterns;
})();
}
/**
* Check if we should run the cleaning step.
*/
shouldClean() {
return (_fs || _load_fs()).exists(path.join(this.config.cwd, (_constants || _load_constants()).CLEAN_FILENAME));
}
/**
* TODO
*/
flatten(patterns) {
var _this5 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
Eif (!_this5.flags.flat) {
return patterns;
}
const flattenedPatterns = [];
for (const name of _this5.resolver.getAllDependencyNamesByLevelOrder(patterns)) {
const infos = _this5.resolver.getAllInfoForPackageName(name).filter(function (manifest) {
const ref = manifest._reference;
invariant(ref, 'expected package reference');
return !ref.ignore;
});
if (infos.length === 0) {
continue;
}
if (infos.length === 1) {
// single version of this package
// take out a single pattern as multiple patterns may have resolved to this package
flattenedPatterns.push(_this5.resolver.patternsByPackage[name][0]);
continue;
}
const options = infos.map(function (info) {
const ref = info._reference;
invariant(ref, 'expected reference');
return {
// TODO `and is required by {PARENT}`,
name: _this5.reporter.lang('manualVersionResolutionOption', ref.patterns.join(', '), info.version),
value: info.version
};
});
const versions = infos.map(function (info) {
return info.version;
});
let version;
const resolutionVersion = _this5.resolutions[name];
if (resolutionVersion && versions.indexOf(resolutionVersion) >= 0) {
// use json `resolution` version
version = resolutionVersion;
} else {
version = yield _this5.reporter.select(_this5.reporter.lang('manualVersionResolution', name), _this5.reporter.lang('answer'), options);
_this5.resolutions[name] = version;
}
flattenedPatterns.push(_this5.resolver.collapseAllVersionsOfPackage(name, version));
}
// save resolutions to their appropriate root manifest
if (Object.keys(_this5.resolutions).length) {
const manifests = yield _this5.config.getRootManifests();
for (const name in _this5.resolutions) {
const version = _this5.resolutions[name];
const patterns = _this5.resolver.patternsByPackage[name];
if (!patterns) {
continue;
}
let manifest;
for (const pattern of patterns) {
manifest = _this5.resolver.getResolvedPattern(pattern);
if (manifest) {
break;
}
}
invariant(manifest, 'expected manifest');
const ref = manifest._reference;
invariant(ref, 'expected reference');
const object = manifests[ref.registry].object;
object.resolutions = object.resolutions || {};
object.resolutions[name] = version;
}
yield _this5.config.saveRootManifests(manifests);
}
return flattenedPatterns;
})();
}
/**
* Check if the loaded lockfile has all the included patterns
*/
lockFileInSync(patterns) {
let inSync = true;
for (const pattern of patterns) {
Eif (!this.lockfile.getLocked(pattern)) {
inSync = false;
break;
}
}
return inSync;
}
/**
* Save updated integrity and lockfiles.
*/
saveLockfileAndIntegrity(patterns) {
var _this6 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// stringify current lockfile
const lockSource = (0, (_stringify || _load_stringify()).default)(_this6.lockfile.getLockfile(_this6.resolver.patterns));
// write integrity hash
yield _this6.writeIntegrityHash(lockSource, patterns);
// --no-lockfile or --pure-lockfile flag
Iif (_this6.flags.lockfile === false || _this6.flags.pureLockfile) {
return;
}
const inSync = _this6.lockFileInSync(patterns);
// remove is followed by install with force on which we rewrite lockfile
Iif (inSync && patterns.length && !_this6.flags.force) {
return;
}
// build lockfile location
const loc = path.join(_this6.config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME);
// write lockfile
yield (_fs || _load_fs()).writeFilePreservingEol(loc, lockSource);
_this6._logSuccessSaveLockfile();
})();
}
_logSuccessSaveLockfile() {
this.reporter.success(this.reporter.lang('savedLockfile'));
}
/**
* Check if the integrity hash of this installation matches one on disk.
*/
matchesIntegrityHash(patterns) {
var _this7 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const loc = yield _this7.getIntegrityHashLocation();
Eif (!(yield (_fs || _load_fs()).exists(loc))) {
return {
actual: '',
expected: '',
loc,
matches: false
};
}
const lockSource = (0, (_stringify || _load_stringify()).default)(_this7.lockfile.getLockfile(_this7.resolver.patterns));
const actual = _this7.generateIntegrityHash(lockSource, patterns);
const expected = (yield (_fs || _load_fs()).readFile(loc)).trim();
return {
actual,
expected,
loc,
matches: actual === expected
};
})();
}
/**
* Get the location of an existing integrity hash. If none exists then return the location where we should
* write a new one.
*/
getIntegrityHashLocation() {
var _this8 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// build up possible folders
const possibleFolders = [];
Iif (_this8.config.modulesFolder) {
possibleFolders.push(_this8.config.modulesFolder);
}
// get a list of registry names to check existence in
let checkRegistryNames = _this8.resolver.usedRegistries;
Eif (!checkRegistryNames.length) {
// we haven't used any registries yet
checkRegistryNames = (_index2 || _load_index2()).registryNames;
}
// ensure we only write to a registry folder that was used
for (const name of checkRegistryNames) {
const loc = path.join(_this8.config.cwd, _this8.config.registries[name].folder);
possibleFolders.push(loc);
}
// if we already have an integrity hash in one of these folders then use it's location otherwise use the
// first folder
const possibles = possibleFolders.map(function (folder) {
return path.join(folder, (_constants || _load_constants()).INTEGRITY_FILENAME);
});
let loc = possibles[0];
for (const possibleLoc of possibles) {
Iif (yield (_fs || _load_fs()).exists(possibleLoc)) {
loc = possibleLoc;
break;
}
}
return loc;
})();
}
/**
* Write the integrity hash of the current install to disk.
*/
writeIntegrityHash(lockSource, patterns) {
var _this9 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const loc = yield _this9.getIntegrityHashLocation();
invariant(loc, 'expected integrity hash location');
yield (_fs || _load_fs()).mkdirp(path.dirname(loc));
yield (_fs || _load_fs()).writeFile(loc, _this9.generateIntegrityHash(lockSource, patterns));
})();
}
/**
* Generate integrity hash of input lockfile.
*/
generateIntegrityHash(lockfile, patterns) {
const opts = [lockfile];
opts.push(`patterns:${patterns.sort((_misc || _load_misc()).sortAlpha).join(',')}`);
Iif (this.flags.flat) {
opts.push('flat');
}
Iif (this.config.production) {
opts.push('production');
}
const linkedModules = this.config.linkedModules;
Iif (linkedModules.length) {
opts.push(`linked:${linkedModules.join(',')}`);
}
const mirror = this.config.getOfflineMirrorPath();
Iif (mirror != null) {
opts.push(`mirror:${mirror}`);
}
return (_crypto || _load_crypto()).hash(opts.join('-'), 'sha256');
}
/**
* Load the dependency graph of the current install. Only does package resolving and wont write to the cwd.
*/
hydrate(fetch) {
var _this10 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const request = yield _this10.fetchRequestFromCwd();
const depRequests = request.requests,
rawPatterns = request.patterns,
ignorePatterns = request.ignorePatterns;
yield _this10.resolver.init(depRequests, _this10.flags.flat);
yield _this10.flatten(rawPatterns);
_this10.markIgnored(ignorePatterns);
if (fetch) {
// fetch packages, should hit cache most of the time
yield _this10.fetcher.init();
yield _this10.compatibility.init();
// expand minimal manifests
for (const manifest of _this10.resolver.getManifests()) {
const ref = manifest._reference;
invariant(ref, 'expected reference');
const loc = _this10.config.generateHardModulePath(ref);
const newPkg = yield _this10.config.readManifest(loc);
yield _this10.resolver.updateManifest(ref, newPkg);
}
}
return request;
})();
}
/**
* Check for updates every day and output a nag message if there's a newer version.
*/
checkUpdate() {
Eif (!process.stdout.isTTY || isCI) {
// don't show upgrade dialog on CI or non-TTY terminals
return;
}
// only check for updates once a day
const lastUpdateCheck = Number(this.config.getOption('lastUpdateCheck')) || 0;
if (lastUpdateCheck && Date.now() - lastUpdateCheck < ONE_DAY) {
return;
}
// don't bug for updates on tagged releases
if (YARN_VERSION.indexOf('-') >= 0) {
return;
}
this._checkUpdate().catch(() => {
// swallow errors
});
}
_checkUpdate() {
var _this11 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
let latestVersion = yield _this11.config.requestManager.request({
url: (_constants || _load_constants()).SELF_UPDATE_VERSION_URL
});
invariant(typeof latestVersion === 'string', 'expected string');
latestVersion = latestVersion.trim();
if (!semver.valid(latestVersion)) {
return;
}
// ensure we only check for updates periodically
_this11.config.registries.yarn.saveHomeConfig({
lastUpdateCheck: Date.now()
});
if (semver.gt(latestVersion, YARN_VERSION)) {
_this11.maybeOutputUpdate = function () {
_this11.reporter.warn(_this11.reporter.lang('yarnOutdated', latestVersion, YARN_VERSION));
const command = getUpdateCommand();
if (command) {
_this11.reporter.info(_this11.reporter.lang('yarnOutdatedCommand'));
_this11.reporter.command(command);
} else {
const installer = getUpdateInstaller();
if (installer) {
_this11.reporter.info(_this11.reporter.lang('yarnOutdatedInstaller', installer));
}
}
};
}
})();
}
/**
* Method to override with a possible upgrade message.
*/
maybeOutputUpdate() {}
}
exports.Install = Install;
function setFlags(commander) {
commander.usage('install [flags]');
commander.option('-g, --global', 'DEPRECATED');
commander.option('-S, --save', 'DEPRECATED - save package to your `dependencies`');
commander.option('-D, --save-dev', 'DEPRECATED - save package to your `devDependencies`');
commander.option('-P, --save-peer', 'DEPRECATED - save package to your `peerDependencies`');
commander.option('-O, --save-optional', 'DEPRECATED - save package to your `optionalDependencies`');
commander.option('-E, --save-exact', 'DEPRECATED');
commander.option('-T, --save-tilde', 'DEPRECATED');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setFlags = exports.run = undefined;
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let getManifests = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags) {
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd);
const install = new (_install || _load_install()).Install((0, (_extends2 || _load_extends()).default)({ skipIntegrity: true }, flags), config, new (_baseReporter || _load_baseReporter()).default(), lockfile);
yield install.hydrate(true);
let manifests = install.resolver.getManifests();
// sort by name
manifests = manifests.sort(function (a, b) {
if (!a.name && !b.name) {
return 0;
}
if (!a.name) {
return 1;
}
if (!b.name) {
return -1;
}
return a.name.localeCompare(b.name);
});
// filter ignored manifests
manifests = manifests.filter(function (manifest) {
const ref = manifest._reference;
return !!ref && !ref.ignore;
});
return manifests;
});
return function getManifests(_x, _x2) {
return _ref.apply(this, arguments);
};
})();
exports.hasWrapper = hasWrapper;
var _baseReporter;
function _load_baseReporter() {
return _baseReporter = _interopRequireDefault(require('../../reporters/base-reporter.js'));
}
var _install;
function _load_install() {
return _install = require('./install.js');
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _buildSubCommands2;
function _load_buildSubCommands() {
return _buildSubCommands2 = _interopRequireDefault(require('./_build-sub-commands.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
function hasWrapper(flags, args) {
return args[0] != 'generate-disclaimer';
}
var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('licenses', {
ls(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const manifests = yield getManifests(config, flags);
if (flags.json) {
const body = [];
for (const _ref2 of manifests) {
const name = _ref2.name,
version = _ref2.version,
license = _ref2.license,
repository = _ref2.repository,
homepage = _ref2.homepage;
const url = repository ? repository.url : homepage;
body.push([name, version, license || 'Unknown', url || 'Unknown']);
}
reporter.table(['Name', 'Version', 'License', 'URL'], body);
} else {
const trees = [];
for (const _ref3 of manifests) {
const name = _ref3.name,
version = _ref3.version,
license = _ref3.license,
repository = _ref3.repository,
homepage = _ref3.homepage;
const children = [];
children.push({ name: `${reporter.format.bold('License:')} ${license || reporter.format.red('UNKNOWN')}` });
const url = repository ? repository.url : homepage;
if (url) {
children.push({ name: `${reporter.format.bold('URL:')} ${url}` });
}
trees.push({
name: `${name}@${version}`,
children
});
}
reporter.tree('licenses', trees);
}
})();
},
generateDisclaimer(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const manifests = yield getManifests(config, flags);
const manifest = yield config.readRootManifest();
// Create a map of license text to manifest so that packages with exactly
// the same license text are grouped together.
const manifestsByLicense = new Map();
for (const manifest of manifests) {
const licenseText = manifest.licenseText;
if (!licenseText) {
continue;
}
if (!manifestsByLicense.has(licenseText)) {
manifestsByLicense.set(licenseText, new Map());
}
const byLicense = manifestsByLicense.get(licenseText);
invariant(byLicense, 'expected value');
byLicense.set(manifest.name, manifest);
}
console.log('THE FOLLOWING SETS FORTH ATTRIBUTION NOTICES FOR THIRD PARTY SOFTWARE THAT MAY BE CONTAINED ' + `IN PORTIONS OF THE ${String(manifest.name).toUpperCase().replace(/-/g, ' ')} PRODUCT.`);
console.log();
for (const _ref4 of manifestsByLicense) {
var _ref5 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref4, 2);
const licenseText = _ref5[0];
const manifests = _ref5[1];
console.log('-----');
console.log();
const names = [];
const urls = [];
for (const _ref6 of manifests) {
var _ref7 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref6, 2);
const name = _ref7[0];
const repository = _ref7[1].repository;
names.push(name);
if (repository && repository.url) {
urls.push(manifests.size === 1 ? repository.url : `${repository.url} (${name})`);
}
}
const heading = [];
heading.push(`The following software may be included in this product: ${names.join(', ')}.`);
if (urls.length > 0) {
heading.push(`A copy of the source code may be downloaded from ${urls.join(', ')}.`);
}
heading.push('This software contains the following license and notice below:');
console.log(heading.join(' '));
console.log();
if (licenseText) {
console.log(licenseText.trim());
} else {
// what do we do here? base it on `license`?
}
console.log();
}
})();
}
});
const run = _buildSubCommands.run,
setFlags = _buildSubCommands.setFlags;
exports.run = run;
exports.setFlags = setFlags;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.getRegistryFolder = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let getRegistryFolder = exports.getRegistryFolder = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, name) {
if (config.modulesFolder) {
return config.modulesFolder;
}
const src = path.join(config.linkFolder, name);
var _ref2 = yield config.readManifest(src);
const _registry = _ref2._registry;
invariant(_registry, 'expected registry');
const registryFolder = config.registries[_registry].folder;
return path.join(config.cwd, registryFolder);
});
return function getRegistryFolder(_x, _x2) {
return _ref.apply(this, arguments);
};
})();
let run = exports.run = (() => {
var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
if (args.length) {
for (const name of args) {
const src = path.join(config.linkFolder, name);
if (yield (_fs || _load_fs()).exists(src)) {
const folder = yield getRegistryFolder(config, name);
const dest = path.join(folder, name);
yield (_fs || _load_fs()).unlink(dest);
yield (_fs || _load_fs()).mkdirp(path.dirname(dest));
yield (_fs || _load_fs()).symlink(src, dest);
reporter.success(reporter.lang('linkRegistered', name));
} else {
throw new (_errors || _load_errors()).MessageError(reporter.lang('linkMissing', name));
}
}
} else {
// add cwd module to the global registry
const manifest = yield config.readRootManifest();
const name = manifest.name;
if (!name) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('unknownPackageName'));
}
const linkLoc = path.join(config.linkFolder, name);
if (yield (_fs || _load_fs()).exists(linkLoc)) {
reporter.warn(reporter.lang('linkCollision', name));
} else {
yield (_fs || _load_fs()).mkdirp(path.dirname(linkLoc));
yield (_fs || _load_fs()).symlink(config.cwd, linkLoc);
// If there is a `bin` defined in the package.json,
// link each bin to the global bin
if (manifest.bin) {
const globalBinFolder = (0, (_global || _load_global()).getBinFolder)(config, flags);
for (const binName in manifest.bin) {
const binSrc = manifest.bin[binName];
const binSrcLoc = path.join(linkLoc, binSrc);
const binDestLoc = path.join(globalBinFolder, binName);
if (yield (_fs || _load_fs()).exists(binDestLoc)) {
reporter.warn(reporter.lang('binLinkCollision', binName));
} else {
yield (_fs || _load_fs()).symlink(binSrcLoc, binDestLoc);
}
}
}
reporter.success(reporter.lang('linkRegistered', name));
reporter.info(reporter.lang('linkInstallMessage', name));
}
}
});
return function run(_x3, _x4, _x5, _x6) {
return _ref3.apply(this, arguments);
};
})();
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _global;
function _load_global() {
return _global = require('./global');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const path = require('path');
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.buildTree = exports.requireLockfile = undefined;
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let buildTree = exports.buildTree = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (resolver, linker, patterns, opts, onlyFresh, ignoreHoisted) {
const treesByKey = {};
const trees = [];
const hoisted = yield linker.getFlatHoistedTree(patterns);
const hoistedByKey = {};
for (const _ref2 of hoisted) {
var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 2);
const key = _ref3[0];
const info = _ref3[1];
hoistedByKey[key] = info;
}
// build initial trees
for (const _ref4 of hoisted) {
var _ref5 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref4, 2);
const info = _ref5[1];
const ref = info.pkg._reference;
const hint = null;
const parent = getParent(info.key, treesByKey);
const children = [];
let depth = 0;
let color = 'bold';
invariant(ref, 'expected reference');
if (onlyFresh) {
let isFresh = false;
for (const pattern of ref.patterns) {
if (resolver.isNewPattern(pattern)) {
isFresh = true;
break;
}
}
if (!isFresh) {
continue;
}
}
if (info.originalKey !== info.key || opts.reqDepth === 0) {
// was hoisted
color = null;
}
// check parent to obtain next depth
if (parent && parent.depth > 0) {
depth = parent.depth + 1;
} else {
depth = 0;
}
const topLevel = opts.reqDepth === 0 && !parent;
const showAll = opts.reqDepth === -1;
const nextDepthIsValid = depth + 1 <= Number(opts.reqDepth);
if (topLevel || nextDepthIsValid || showAll) {
treesByKey[info.key] = {
name: `${info.pkg.name}@${info.pkg.version}`,
children,
hint,
color,
depth
};
}
// add in dummy children for hoisted dependencies
const nextChildDepthIsValid = depth + 1 < Number(opts.reqDepth);
invariant(ref, 'expected reference');
if (!ignoreHoisted && nextDepthIsValid || showAll) {
for (const pattern of resolver.dedupePatterns(ref.dependencies)) {
const pkg = resolver.getStrictResolvedPattern(pattern);
if (!hoistedByKey[`${info.key}#${pkg.name}`] && (nextChildDepthIsValid || showAll)) {
children.push({
name: pattern,
color: 'dim',
shadow: true
});
}
}
}
}
// add children
for (const _ref6 of hoisted) {
var _ref7 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref6, 2);
const info = _ref7[1];
const tree = treesByKey[info.key];
const parent = getParent(info.key, treesByKey);
if (!tree) {
continue;
}
if (info.key.split('#').length === 1) {
trees.push(tree);
continue;
}
if (parent) {
parent.children.push(tree);
}
}
return { trees, count: buildCount(trees) };
});
return function buildTree(_x, _x2, _x3, _x4, _x5, _x6) {
return _ref.apply(this, arguments);
};
})();
let run = exports.run = (() => {
var _ref8 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd, reporter);
const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile);
var _ref9 = yield install.fetchRequestFromCwd();
const depRequests = _ref9.requests,
patterns = _ref9.patterns;
yield install.resolver.init(depRequests, install.flags.flat);
const opts = {
reqDepth: getReqDepth(flags.depth)
};
var _ref10 = yield buildTree(install.resolver, install.linker, patterns, opts);
let trees = _ref10.trees;
if (args.length) {
trees = trees.filter(function (tree) {
return filterTree(tree, args);
});
}
reporter.tree('list', trees);
});
return function run(_x7, _x8, _x9, _x10) {
return _ref8.apply(this, arguments);
};
})();
exports.getParent = getParent;
exports.setFlags = setFlags;
exports.getReqDepth = getReqDepth;
exports.filterTree = filterTree;
var _install;
function _load_install() {
return _install = require('./install.js');
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const requireLockfile = exports.requireLockfile = true;
function buildCount(trees) {
if (!trees || !trees.length) {
return 0;
}
let count = 0;
for (const tree of trees) {
if (tree.shadow) {
continue;
}
count++;
count += buildCount(tree.children);
}
return count;
}
function getParent(key, treesByKey) {
const parentKey = key.split('#').slice(0, -1).join('#');
return treesByKey[parentKey];
}
function setFlags(commander) {
commander.option('--depth [depth]', 'Limit the depth of the shown dependencies');
}
function getReqDepth(inputDepth) {
return inputDepth && /^\d+$/.test(inputDepth) ? Number(inputDepth) : -1;
}
function filterTree(tree, filters) {
if (tree.children) {
tree.children = tree.children.filter(child => filterTree(child, filters));
}
const notDim = tree.color !== 'dim';
const found = filters.indexOf(tree.name.slice(0, tree.name.lastIndexOf('@'))) > -1;
const hasChildren = tree.children == null ? false : tree.children.length > 0;
return notDim && (found || hasChildren);
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.getToken = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let getCredentials = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter) {
var _config$registries$ya = config.registries.yarn.config;
let username = _config$registries$ya.username,
email = _config$registries$ya.email;
if (username) {
reporter.info(`${reporter.lang('npmUsername')}: ${username}`);
} else {
username = yield reporter.question(reporter.lang('npmUsername'));
if (!username) {
return null;
}
}
if (email) {
reporter.info(`${reporter.lang('npmUsername')}: ${email}`);
} else {
email = yield reporter.question(reporter.lang('npmEmail'));
if (!email) {
return null;
}
}
yield config.registries.yarn.saveHomeConfig({ username, email });
return { username, email };
});
return function getCredentials(_x, _x2) {
return _ref.apply(this, arguments);
};
})();
let getToken = exports.getToken = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter) {
let name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
const auth = config.registries.npm.getAuth(name);
if (auth) {
config.registries.npm.setToken(auth);
return function revoke() {
reporter.info(reporter.lang('notRevokingConfigToken'));
return Promise.resolve();
};
}
const env = process.env.YARN_AUTH_TOKEN || process.env.NPM_AUTH_TOKEN;
if (env) {
config.registries.npm.setToken(`Bearer ${env}`);
return function revoke() {
reporter.info(reporter.lang('notRevokingEnvToken'));
return Promise.resolve();
};
}
//
const creds = yield getCredentials(config, reporter);
if (!creds) {
reporter.warn(reporter.lang('loginAsPublic'));
return function revoke() {
reporter.info(reporter.lang('noTokenToRevoke'));
return Promise.resolve();
};
}
const username = creds.username,
email = creds.email;
const password = yield reporter.question(reporter.lang('npmPassword'), { password: true, required: true });
//
const userobj = {
_id: `org.couchdb.user:${username}`,
name: username,
password,
email,
type: 'user',
roles: [],
date: new Date().toISOString()
};
//
const res = yield config.registries.npm.request(`-/user/org.couchdb.user:${encodeURIComponent(username)}`, {
method: 'PUT',
body: userobj,
auth: { username, password, email }
});
if (res && res.ok) {
reporter.success(reporter.lang('loggedIn'));
const token = res.token;
config.registries.npm.setToken(`Bearer ${token}`);
return (() => {
var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
reporter.success(reporter.lang('revokedToken'));
yield config.registries.npm.request(`-/user/token/${token}`, {
method: 'DELETE'
});
});
function revoke() {
return _ref3.apply(this, arguments);
}
return revoke;
})();
} else {
throw new (_errors || _load_errors()).MessageError(reporter.lang('incorrectCredentials'));
}
});
return function getToken(_x3, _x4) {
return _ref2.apply(this, arguments);
};
})();
let run = exports.run = (() => {
var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
yield getCredentials(config, reporter);
});
return function run(_x6, _x7, _x8, _x9) {
return _ref4.apply(this, arguments);
};
})();
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
yield config.registries.yarn.saveHomeConfig({
username: undefined,
email: undefined
});
reporter.success(reporter.lang('clearedCredentials'));
});
return function run(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.requireLockfile = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd);
const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile);
let deps = yield (_packageRequest || _load_packageRequest()).default.getOutdatedPackages(lockfile, install, config, reporter);
if (args.length) {
const requested = new Set(args);
deps = deps.filter(function (_ref2) {
let name = _ref2.name;
return requested.has(name);
});
}
const getNameFromHint = function (hint) {
return hint ? `${hint}Dependencies` : 'dependencies';
};
const getColorFromVersion = function (_ref3) {
let current = _ref3.current,
wanted = _ref3.wanted,
name = _ref3.name;
return current === wanted ? reporter.format.yellow(name) : reporter.format.red(name);
};
if (deps.length) {
const body = deps.map(function (info) {
return [getColorFromVersion(info), info.current, reporter.format.green(info.wanted), reporter.format.magenta(info.latest), getNameFromHint(info.hint), reporter.format.cyan(info.url)];
});
reporter.table(['Package', 'Current', 'Wanted', 'Latest', 'Package Type', 'URL'], body);
}
return Promise.resolve();
});
return function run(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
exports.setFlags = setFlags;
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('../../package-request.js'));
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _install;
function _load_install() {
return _install = require('./install.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const requireLockfile = exports.requireLockfile = true;
function setFlags(commander) {
commander.usage('outdated [packages ...]');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setFlags = exports.run = exports.mutate = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let mutate = exports.mutate = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (args, config, reporter, buildMessages, mutator) {
if (args.length !== 2 && args.length !== 1) {
return false;
}
const username = args.shift();
const name = yield (0, (_tag || _load_tag()).getName)(args, config);
if (!(0, (_validate || _load_validate()).isValidPackageName)(name)) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidPackageName'));
}
const msgs = buildMessages(username, name);
reporter.step(1, 3, reporter.lang('loggingIn'));
const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name);
reporter.step(2, 3, msgs.info);
const user = yield config.registries.npm.request(`-/user/org.couchdb.user:${username}`);
let error = false;
if (user) {
// get package
const pkg = yield config.registries.npm.request((_npmRegistry || _load_npmRegistry()).default.escapeName(name));
if (pkg) {
pkg.maintainers = pkg.maintainers || [];
error = mutator({ name: user.name, email: user.email }, pkg);
} else {
error = true;
reporter.error(reporter.lang('unknownPackage', name));
}
// update package
if (pkg && !error) {
const res = yield config.registries.npm.request(`${(_npmRegistry || _load_npmRegistry()).default.escapeName(name)}/-rev/${pkg._rev}`, {
method: 'PUT',
body: {
_id: pkg._id,
_rev: pkg._rev,
maintainers: pkg.maintainers
}
});
if (res != null && res.success) {
reporter.success(msgs.success);
} else {
error = true;
reporter.error(msgs.error);
}
}
} else {
error = true;
reporter.error(reporter.lang('unknownUser', username));
}
reporter.step(3, 3, reporter.lang('revokingToken'));
yield revoke();
if (error) {
throw new Error();
} else {
return true;
}
});
return function mutate(_x, _x2, _x3, _x4, _x5) {
return _ref.apply(this, arguments);
};
})();
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _buildSubCommands2;
function _load_buildSubCommands() {
return _buildSubCommands2 = _interopRequireDefault(require('./_build-sub-commands.js'));
}
var _validate;
function _load_validate() {
return _validate = require('../../util/normalize-manifest/validate.js');
}
var _tag;
function _load_tag() {
return _tag = require('./tag.js');
}
var _login;
function _load_login() {
return _login = require('./login.js');
}
var _npmRegistry;
function _load_npmRegistry() {
return _npmRegistry = _interopRequireDefault(require('../../registries/npm-registry.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('owner', {
add(config, reporter, flags, args) {
return mutate(args, config, reporter, (username, name) => ({
info: reporter.lang('ownerAdding', username, name),
success: reporter.lang('ownerAdded'),
error: reporter.lang('ownerAddingFailed')
}), (user, pkg) => {
for (const owner of pkg.maintainers) {
if (owner.name === user) {
reporter.error(reporter.lang('ownerAlready'));
return true;
}
}
pkg.maintainers.push(user);
return false;
});
},
rm(config, reporter, flags, args) {
return mutate(args, config, reporter, (username, name) => ({
info: reporter.lang('ownerRemoving', username, name),
success: reporter.lang('ownerRemoved'),
error: reporter.lang('ownerRemoveError')
}), (user, pkg) => {
let found = false;
pkg.maintainers = pkg.maintainers.filter(o => {
const match = o.name === user.name;
found = found || match;
return !match;
});
if (!found) {
reporter.error(reporter.lang('userNotAnOwner', user.name));
}
return found;
});
},
ls(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (args.length > 1) {
return false;
}
const name = yield (0, (_tag || _load_tag()).getName)(args, config);
reporter.step(1, 3, reporter.lang('loggingIn'));
const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name);
reporter.step(2, 3, reporter.lang('ownerGetting', name));
const pkg = yield config.registries.npm.request(name);
if (pkg) {
const owners = pkg.maintainers;
if (!owners || !owners.length) {
reporter.warn(reporter.lang('ownerNone'));
} else {
for (const owner of owners) {
reporter.info(`${owner.name} <${owner.email}>`);
}
}
} else {
reporter.error(reporter.lang('ownerGettingFailed'));
}
reporter.step(3, 3, reporter.lang('revokingToken'));
yield revoke();
if (pkg) {
return true;
} else {
throw new Error();
}
})();
}
}, ['add <user> [[<@scope>/]<pkg>]', 'rm <user> [[<@scope>/]<pkg>]', 'ls [<@scope>/]<pkg>']);
const run = _buildSubCommands.run,
setFlags = _buildSubCommands.setFlags;
exports.run = run;
exports.setFlags = setFlags;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.pack = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let pack = exports.pack = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, dir) {
const pkg = yield config.readRootManifest();
const bundledDependencies = pkg.bundledDependencies,
onlyFiles = pkg.files;
// inlude required files
let filters = NEVER_IGNORE.slice();
// include default filters unless `files` is used
if (!onlyFiles) {
filters = filters.concat(DEFAULT_IGNORE);
}
// include bundledDependencies
if (bundledDependencies) {
const folder = config.getFolder(pkg);
filters = (0, (_filter || _load_filter()).ignoreLinesToRegex)(bundledDependencies.map(function (name) {
return `!${folder}/${name}`;
}), '.');
}
// `files` field
if (onlyFiles) {
let lines = ['*', // ignore all files except those that are explicitly included with a negation filter
'.*'];
lines = lines.concat(onlyFiles.map(function (filename) {
return `!${filename}`;
}));
const regexes = (0, (_filter || _load_filter()).ignoreLinesToRegex)(lines, '.');
filters = filters.concat(regexes);
}
//
const files = yield (_fs || _load_fs()).walk(config.cwd, null, new Set(FOLDERS_IGNORE));
// create ignores
for (const file of files) {
if (IGNORE_FILENAMES.indexOf(path.basename(file.relative)) >= 0) {
const raw = yield (_fs || _load_fs()).readFile(file.absolute);
const lines = raw.split('\n');
const regexes = (0, (_filter || _load_filter()).ignoreLinesToRegex)(lines, path.dirname(file.relative));
filters = filters.concat(regexes);
}
}
// files to definently keep, takes precedence over ignore filter
const keepFiles = new Set();
// files to definently ignore
const ignoredFiles = new Set();
// list of files that didn't match any of our patterns, if a directory in the chain above was matched
// then we should inherit it
const possibleKeepFiles = new Set();
// apply filters
(0, (_filter || _load_filter()).sortFilter)(files, filters, keepFiles, possibleKeepFiles, ignoredFiles);
const packer = tar.pack();
const compressor = packer.pipe(new zlib.Gzip());
yield addEntry(packer, {
name: 'package',
type: 'directory'
});
for (const name of keepFiles) {
const loc = path.join(config.cwd, name);
const stat = yield (_fs || _load_fs()).lstat(loc);
let type;
let buffer;
let linkname;
if (stat.isDirectory()) {
type = 'directory';
} else if (stat.isFile()) {
buffer = yield (_fs || _load_fs()).readFileRaw(loc);
type = 'file';
} else if (stat.isSymbolicLink()) {
type = 'symlink';
linkname = yield (_fs || _load_fs()).readlink(loc);
} else {
throw new Error();
}
const entry = {
name: `package/${name}`,
size: stat.size,
mode: stat.mode,
mtime: stat.mtime,
type,
linkname
};
yield addEntry(packer, entry, buffer);
}
packer.finalize();
return compressor;
});
return function pack(_x, _x2) {
return _ref.apply(this, arguments);
};
})();
let run = exports.run = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
const pkg = yield config.readRootManifest();
if (!pkg.name) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('noName'));
}
if (!pkg.version) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('noVersion'));
}
const normaliseScope = function (name) {
return name[0] === '@' ? name.substr(1).replace('/', '-') : name;
};
const filename = flags.filename || path.join(config.cwd, `${normaliseScope(pkg.name)}-v${pkg.version}.tgz`);
const stream = yield pack(config, config.cwd);
yield new Promise(function (resolve, reject) {
stream.pipe(fs2.createWriteStream(filename));
stream.on('error', reject);
stream.on('close', resolve);
});
reporter.success(reporter.lang('packWroteTarball', filename));
});
return function run(_x3, _x4, _x5, _x6) {
return _ref2.apply(this, arguments);
};
})();
exports.setFlags = setFlags;
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _filter;
function _load_filter() {
return _filter = require('../../util/filter.js');
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const zlib = require('zlib');
const path = require('path');
const tar = require('tar-stream');
const fs2 = require('fs');
const IGNORE_FILENAMES = ['.yarnignore', '.npmignore', '.gitignore'];
const FOLDERS_IGNORE = [
// never allow version control folders
'.git', 'CVS', '.svn', '.hg', 'node_modules'];
const DEFAULT_IGNORE = (0, (_filter || _load_filter()).ignoreLinesToRegex)([...FOLDERS_IGNORE,
// ignore cruft
'yarn.lock', '.lock-wscript', '.wafpickle-{0..9}', '*.swp', '._*', 'npm-debug.log', 'yarn-error.log', '.npmrc', '.yarnrc', '.npmignore', '.gitignore', '.DS_Store']);
const NEVER_IGNORE = (0, (_filter || _load_filter()).ignoreLinesToRegex)([
// never ignore these files
'!/package.json', '!/readme*', '!/+(license|licence)*', '!/+(changes|changelog|history)*']);
function addEntry(packer, entry, buffer) {
return new Promise((resolve, reject) => {
packer.entry(entry, buffer, function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
function setFlags(commander) {
commander.option('-f, --filename <filename>', 'filename');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let publish = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, pkg, flags, dir) {
// validate access argument
const access = flags.access;
if (access && access !== 'public' && access !== 'restricted') {
throw new (_errors || _load_errors()).MessageError(config.reporter.lang('invalidAccess'));
}
// get tarball stream
const stat = yield (_fs || _load_fs()).lstat(dir);
let stream;
if (stat.isDirectory()) {
stream = yield (0, (_pack || _load_pack()).pack)(config, dir);
} else if (stat.isFile()) {
stream = fs2.createReadStream(dir);
} else {
throw new Error("Don't know how to handle this file type");
}
invariant(stream, 'expected stream');
const buffer = yield new Promise(function (resolve, reject) {
stream.pipe(new (_stream || _load_stream()).ConcatStream(resolve)).on('error', reject);
});
// copy normalized package and remove internal keys as they may be sensitive or yarn specific
pkg = Object.assign({}, pkg);
for (const key in pkg) {
if (key[0] === '_') {
delete pkg[key];
}
}
const tag = flags.tag || 'latest';
const tbName = `${pkg.name}-${pkg.version}.tgz`;
const tbURI = `${pkg.name}/-/${tbName}`;
// TODO this might modify package.json, do we need to reload it?
yield config.executeLifecycleScript('prepublish');
// create body
const root = {
_id: pkg.name,
access: flags.access,
name: pkg.name,
description: pkg.description,
'dist-tags': {
[tag]: pkg.version
},
versions: {
[pkg.version]: pkg
},
readme: pkg.readme || '',
_attachments: {
[tbName]: {
'content_type': 'application/octet-stream',
data: buffer.toString('base64'),
length: buffer.length
}
}
};
pkg._id = `${pkg.name}@${pkg.version}`;
pkg.dist = pkg.dist || {};
pkg.dist.shasum = crypto.createHash('sha1').update(buffer).digest('hex');
const registry = String(config.getOption('registry'));
pkg.dist.tarball = url.resolve(registry, tbURI).replace(/^https:\/\//, 'http://');
// publish package
const res = yield config.registries.npm.request((_npmRegistry || _load_npmRegistry()).default.escapeName(pkg.name), {
method: 'PUT',
body: root
});
if (res != null && res.success) {
yield config.executeLifecycleScript('publish');
yield config.executeLifecycleScript('postpublish');
} else {
throw new (_errors || _load_errors()).MessageError(config.reporter.lang('publishFail'));
}
});
return function publish(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
let run = exports.run = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
// validate package fields that are required for publishing
const pkg = yield config.readRootManifest();
if (pkg.private) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('publishPrivate'));
}
if (!pkg.name) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('noName'));
}
// validate arguments
const dir = args[0] || config.cwd;
if (args.length > 1) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('tooManyArguments', 1));
}
if (!(yield (_fs || _load_fs()).exists(dir))) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('unknownFolderOrTarball'));
}
//
reporter.step(1, 4, reporter.lang('bumpingVersion'));
const commitVersion = yield (0, (_version || _load_version()).setVersion)(config, reporter, flags, args, false);
//
reporter.step(2, 4, reporter.lang('loggingIn'));
const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, pkg.name);
//
reporter.step(3, 4, reporter.lang('publishing'));
yield publish(config, pkg, flags, dir);
yield commitVersion();
reporter.success(reporter.lang('published'));
//
reporter.step(4, 4, reporter.lang('revokingToken'));
yield revoke();
});
return function run(_x5, _x6, _x7, _x8) {
return _ref2.apply(this, arguments);
};
})();
exports.setFlags = setFlags;
var _npmRegistry;
function _load_npmRegistry() {
return _npmRegistry = _interopRequireDefault(require('../../registries/npm-registry.js'));
}
var _stream;
function _load_stream() {
return _stream = require('../../util/stream.js');
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _version;
function _load_version() {
return _version = require('./version.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _pack;
function _load_pack() {
return _pack = require('./pack.js');
}
var _login;
function _load_login() {
return _login = require('./login.js');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const crypto = require('crypto');
const url = require('url');
const fs2 = require('fs');
function setFlags(commander) {
(0, (_version || _load_version()).setFlags)(commander);
commander.usage('publish [<tarball>|<folder>] [--tag <tag>] [--access <public|restricted>]');
commander.option('--access [access]', 'access');
commander.option('--tag [tag]', 'tag');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.requireLockfile = undefined;
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
if (!args.length) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('tooFewArguments', 1));
}
const totalSteps = args.length + 1;
let step = 0;
// load manifests
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd);
const rootManifests = yield config.getRootManifests();
const manifests = [];
for (const name of args) {
reporter.step(++step, totalSteps, `Removing module ${name}`);
let found = false;
for (const registryName of Object.keys((_index || _load_index()).registries)) {
const registry = config.registries[registryName];
const object = rootManifests[registryName].object;
for (const type of (_constants || _load_constants()).DEPENDENCY_TYPES) {
const deps = object[type];
if (deps && deps[name]) {
found = true;
delete deps[name];
}
}
const possibleManifestLoc = path.join(config.cwd, registry.folder, name);
if (yield (_fs || _load_fs()).exists(possibleManifestLoc)) {
manifests.push([possibleManifestLoc, yield config.readManifest(possibleManifestLoc, registryName)]);
}
}
if (!found) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('moduleNotInManifest'));
}
}
// save manifests
yield config.saveRootManifests(rootManifests);
// run hooks - npm runs these one after another
for (const action of ['preuninstall', 'uninstall', 'postuninstall']) {
for (const _ref2 of manifests) {
var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 1);
const loc = _ref3[0];
yield config.executeLifecycleScript(action, loc);
}
}
// reinstall so we can get the updated lockfile
reporter.step(++step, totalSteps, reporter.lang('uninstallRegenerate'));
const reinstall = new (_install || _load_install()).Install((0, (_extends2 || _load_extends()).default)({ force: true }, flags), config, new (_index2 || _load_index2()).NoopReporter(), lockfile);
yield reinstall.init();
//
reporter.success(reporter.lang('uninstalledPackages'));
});
return function run(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _index;
function _load_index() {
return _index = require('../../registries/index.js');
}
var _install;
function _load_install() {
return _install = require('./install.js');
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _index2;
function _load_index2() {
return _index2 = require('../../reporters/index.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../../constants.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
const requireLockfile = exports.requireLockfile = true;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = undefined;
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
let runCommand = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (args) {
const action = args.shift();
const actions = [`pre${action}`, action, `post${action}`];
// build up list of commands
const cmds = [];
for (const action of actions) {
const cmd = scripts[action];
if (cmd) {
cmds.push([action, cmd]);
}
}
if (cmds.length) {
for (const _ref3 of cmds) {
var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2);
const stage = _ref4[0];
const cmd = _ref4[1];
// only tack on trailing arguments for default script, ignore for pre and post - #1595
const defaultScriptCmd = `${cmd} ${sanitizedArgs(args).join(' ')}`;
const cmdWithArgs = stage === action ? defaultScriptCmd : cmd;
yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execCommand)(stage, config, cmdWithArgs, config.cwd);
}
} else {
let suggestion;
for (const commandName in scripts) {
const steps = leven(commandName, action);
if (steps < 2) {
suggestion = commandName;
}
}
let msg = `Command ${JSON.stringify(action)} not found.`;
if (suggestion) {
msg += ` Did you mean ${JSON.stringify(suggestion)}?`;
}
throw new (_errors || _load_errors()).MessageError(msg);
}
});
return function runCommand(_x5) {
return _ref2.apply(this, arguments);
};
})();
// list possible scripts if none specified
// build up a list of possible scripts
const pkg = yield config.readManifest(config.cwd);
const scripts = (0, (_map || _load_map()).default)();
const binCommands = [];
const visitedBinFolders = new Set();
let pkgCommands = [];
for (const registry of Object.keys((_index || _load_index()).registries)) {
const binFolder = path.join(config.cwd, config.registries[registry].folder, '.bin');
if (!visitedBinFolders.has(binFolder)) {
if (yield (_fs || _load_fs()).exists(binFolder)) {
for (const name of yield (_fs || _load_fs()).readdir(binFolder)) {
binCommands.push(name);
scripts[name] = `"${path.join(binFolder, name)}"`;
}
}
visitedBinFolders.add(binFolder);
}
}
const pkgScripts = pkg.scripts;
const cmdHints = {};
if (pkgScripts) {
// inherit `scripts` from manifest
pkgCommands = Object.keys(pkgScripts).sort();
// add command hints (what the actual yarn command will do)
for (const cmd of pkgCommands) {
cmdHints[cmd] = pkgScripts[cmd] || '';
}
Object.assign(scripts, pkg.scripts);
}
if (args.length === 0) {
reporter.error(reporter.lang('commandNotSpecified'));
reporter.info(`${reporter.lang('binCommands') + binCommands.join(', ')}`);
reporter.info(`${reporter.lang('possibleCommands')}`);
reporter.list('possibleCommands', pkgCommands, cmdHints);
yield reporter.question(reporter.lang('commandQuestion')).then(function (answer) {
return runCommand(answer.split(' '));
}, function () {
return reporter.error(reporter.lang('commandNotSpecified'));
});
return Promise.resolve();
} else {
return yield runCommand(args);
}
});
return function run(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
var _executeLifecycleScript;
function _load_executeLifecycleScript() {
return _executeLifecycleScript = require('../../util/execute-lifecycle-script.js');
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _index;
function _load_index() {
return _index = require('../../resolvers/index.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('../../util/map.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const leven = require('leven');
const path = require('path');
function sanitizedArgs(args) {
const newArgs = [];
for (let arg of args) {
if (/\s/.test(arg)) {
arg = `"${arg}"`;
}
newArgs.push(arg);
}
return newArgs;
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.examples = exports.setFlags = exports.run = exports.getName = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let getName = exports.getName = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (args, config) {
let name = args.shift();
if (!name) {
const pkg = yield config.readRootManifest();
name = pkg.name;
}
if (name) {
if (!(0, (_validate || _load_validate()).isValidPackageName)(name)) {
throw new (_errors || _load_errors()).MessageError(config.reporter.lang('invalidPackageName'));
}
return (_npmRegistry || _load_npmRegistry()).default.escapeName(name);
} else {
throw new (_errors || _load_errors()).MessageError(config.reporter.lang('unknownPackageName'));
}
});
return function getName(_x, _x2) {
return _ref.apply(this, arguments);
};
})();
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('../../package-request.js'));
}
var _buildSubCommands2;
function _load_buildSubCommands() {
return _buildSubCommands2 = _interopRequireDefault(require('./_build-sub-commands.js'));
}
var _login;
function _load_login() {
return _login = require('./login.js');
}
var _npmRegistry;
function _load_npmRegistry() {
return _npmRegistry = _interopRequireDefault(require('../../registries/npm-registry.js'));
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _validate;
function _load_validate() {
return _validate = require('../../util/normalize-manifest/validate.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('tag', {
add(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (args.length !== 2) {
return false;
}
var _PackageRequest$norma = (_packageRequest || _load_packageRequest()).default.normalizePattern(args.shift());
const name = _PackageRequest$norma.name,
range = _PackageRequest$norma.range,
hasVersion = _PackageRequest$norma.hasVersion;
if (!hasVersion) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('requiredVersionInRange'));
}
if (!(0, (_validate || _load_validate()).isValidPackageName)(name)) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidPackageName'));
}
const tag = args.shift();
reporter.step(1, 3, reporter.lang('loggingIn'));
const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name);
reporter.step(2, 3, reporter.lang('creatingTag', tag, range));
const result = yield config.registries.npm.request(`-/package/${(_npmRegistry || _load_npmRegistry()).default.escapeName(name)}/dist-tags/${encodeURI(tag)}`, {
method: 'PUT',
body: range
});
if (result != null && result.ok) {
reporter.success(reporter.lang('createdTag'));
} else {
reporter.error(reporter.lang('createdTagFail'));
}
reporter.step(3, 3, reporter.lang('revokingToken'));
yield revoke();
if (result != null && result.ok) {
return true;
} else {
throw new Error();
}
})();
},
rm(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (args.length !== 2) {
return false;
}
const name = yield getName(args, config);
const tag = args.shift();
reporter.step(1, 3, reporter.lang('loggingIn'));
const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name);
reporter.step(2, 3, reporter.lang('deletingTags'));
const result = yield config.registries.npm.request(`-/package/${name}/dist-tags/${encodeURI(tag)}`, {
method: 'DELETE'
});
if (result === false) {
reporter.error(reporter.lang('deletedTagFail'));
} else {
reporter.success(reporter.lang('deletedTag'));
}
reporter.step(3, 3, reporter.lang('revokingToken'));
yield revoke();
if (result === false) {
throw new Error();
} else {
return true;
}
})();
},
ls(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const name = yield getName(args, config);
reporter.step(1, 3, reporter.lang('loggingIn'));
const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name);
reporter.step(2, 3, reporter.lang('gettingTags'));
const tags = yield config.registries.npm.request(`-/package/${name}/dist-tags`);
if (tags) {
reporter.info(`Package ${name}`);
for (const name in tags) {
reporter.info(`${name}: ${tags[name]}`);
}
}
reporter.step(3, 3, reporter.lang('revokingToken'));
yield revoke();
if (!tags) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('packageNotFoundRegistry', name, 'npm'));
}
})();
}
}, ['add <pkg>@<version> [<tag>]', 'rm <pkg> <tag>', 'ls [<pkg>]']);
const run = _buildSubCommands.run,
setFlags = _buildSubCommands.setFlags,
examples = _buildSubCommands.examples;
exports.run = run;
exports.setFlags = setFlags;
exports.examples = examples;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 5 5 5 1 3 3 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setFlags = exports.run = undefined;
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _toArray2;
function _load_toArray() {
return _toArray2 = _interopRequireDefault(require('babel-runtime/helpers/toArray'));
}
var _buildSubCommands2;
function _load_buildSubCommands() {
return _buildSubCommands2 = _interopRequireDefault(require('./_build-sub-commands.js'));
}
var _login;
function _load_login() {
return _login = require('./login.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function explodeScopeTeam(arg, requireTeam, reporter) {
var _arg$split = arg.split(':'),
_arg$split2 = (0, (_toArray2 || _load_toArray()).default)(_arg$split);
const scope = _arg$split2[0],
team = _arg$split2[1],
parts = _arg$split2.slice(2);
if (parts.length) {
return false;
}
if (requireTeam && !team) {
return false;
}
return {
scope: scope || '',
team: team || '',
user: ''
};
}
function wrapRequired(callback, requireTeam) {
return (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
if (!args.length) {
return false;
}
const parts = explodeScopeTeam(args[0], requireTeam, reporter);
if (!parts) {
return false;
}
reporter.step(1, 3, reporter.lang('loggingIn'));
const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter);
const res = yield callback(parts, config, reporter, flags, args);
if (!res) {
return res;
}
reporter.step(3, 3, reporter.lang('revokingToken'));
yield revoke();
return true;
});
return function (_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
}
function wrapRequiredTeam(callback) {
let requireTeam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
return wrapRequired(function (parts, config, reporter, flags, args) {
if (args.length === 1) {
return callback(parts, config, reporter, flags, args);
} else {
return false;
}
}, requireTeam);
}
function wrapRequiredUser(callback) {
return wrapRequired(function (parts, config, reporter, flags, args) {
if (args.length === 2) {
return callback((0, (_extends2 || _load_extends()).default)({
user: args[1]
}, parts), config, reporter, flags, args);
} else {
return false;
}
}, true);
}
var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('team', {
create: wrapRequiredTeam((() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) {
reporter.step(2, 3, reporter.lang('teamCreating'));
reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}`, {
method: 'PUT',
body: {
team: parts.team
}
})));
return true;
});
return function (_x6, _x7, _x8, _x9, _x10) {
return _ref2.apply(this, arguments);
};
})()),
destroy: wrapRequiredTeam((() => {
var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) {
reporter.step(2, 3, reporter.lang('teamRemoving'));
reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}`, {
method: 'DELETE'
})));
return true;
});
return function (_x11, _x12, _x13, _x14, _x15) {
return _ref3.apply(this, arguments);
};
})()),
add: wrapRequiredUser((() => {
var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) {
reporter.step(2, 3, reporter.lang('teamAddingUser'));
reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}/user`, {
method: 'PUT',
body: {
user: parts.user
}
})));
return true;
});
return function (_x16, _x17, _x18, _x19, _x20) {
return _ref4.apply(this, arguments);
};
})()),
rm: wrapRequiredUser((() => {
var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) {
reporter.step(2, 3, reporter.lang('teamRemovingUser'));
reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}/user`, {
method: 'DELETE',
body: {
user: parts.user
}
})));
return true;
});
return function (_x21, _x22, _x23, _x24, _x25) {
return _ref5.apply(this, arguments);
};
})()),
ls: wrapRequiredTeam((() => {
var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) {
reporter.step(2, 3, reporter.lang('teamListing'));
const uriParams = '?format=cli';
if (parts.team) {
reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}/user${uriParams}`)));
} else {
reporter.inspect((yield config.registries.npm.request(`org/${parts.scope}/team${uriParams}`)));
}
return true;
});
return function (_x26, _x27, _x28, _x29, _x30) {
return _ref6.apply(this, arguments);
};
})(), false)
}, ['create <scope:team>', 'destroy <scope:team>', 'add <scope:team> <user>', 'rm <scope:team> <user>', 'ls <scope>|<scope:team>']);
const run = _buildSubCommands.run,
setFlags = _buildSubCommands.setFlags;
exports.run = run;
exports.setFlags = setFlags;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
if (args.length) {
for (const name of args) {
const linkLoc = path.join(config.linkFolder, name);
if (yield (_fs || _load_fs()).exists(linkLoc)) {
yield (_fs || _load_fs()).unlink(path.join((yield (0, (_link || _load_link()).getRegistryFolder)(config, name)), name));
reporter.success(reporter.lang('linkUnregistered', name));
} else {
throw new (_errors || _load_errors()).MessageError(reporter.lang('linkMissing', name));
}
}
} else {
// remove from registry
const manifest = yield config.readRootManifest();
const name = manifest.name;
if (!name) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('unknownPackageName'));
}
const linkLoc = path.join(config.linkFolder, name);
if (yield (_fs || _load_fs()).exists(linkLoc)) {
// If there is a `bin` defined in the package.json,
// link each bin to the global bin
if (manifest.bin) {
const globalBinFolder = (0, (_global || _load_global()).getBinFolder)(config, flags);
for (const binName in manifest.bin) {
const binDestLoc = path.join(globalBinFolder, binName);
if (yield (_fs || _load_fs()).exists(binDestLoc)) {
yield (_fs || _load_fs()).unlink(binDestLoc);
}
}
}
yield (_fs || _load_fs()).unlink(linkLoc);
reporter.success(reporter.lang('linkUnregistered', name));
} else {
throw new (_errors || _load_errors()).MessageError(reporter.lang('linkMissing', name));
}
}
});
return function run(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _link;
function _load_link() {
return _link = require('./link.js');
}
var _global;
function _load_global() {
return _global = require('./global');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.requireLockfile = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
// Prompt user with Inquirer
let prompt = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (choices) {
let pageSize;
if (process.stdout instanceof tty.WriteStream) {
pageSize = process.stdout.rows - 2;
}
const answers = yield (_inquirer || _load_inquirer()).default.prompt([{
name: 'packages',
type: 'checkbox',
message: 'Choose which packages to update.',
choices,
pageSize,
validate: function (answer) {
return !!answer.length || 'You must choose at least one package.';
}
}]);
return answers.packages;
});
return function prompt(_x) {
return _ref.apply(this, arguments);
};
})();
let run = exports.run = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd);
const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile);
const deps = yield (_packageRequest || _load_packageRequest()).default.getOutdatedPackages(lockfile, install, config, reporter);
if (!deps.length) {
reporter.success(reporter.lang('allDependenciesUpToDate'));
return;
}
const getNameFromHint = function (hint) {
return hint ? `${hint}Dependencies` : 'dependencies';
};
const maxLengthArr = { name: 0, current: 0, latest: 0 };
deps.forEach(function (dep) {
return ['name', 'current', 'latest'].forEach(function (key) {
maxLengthArr[key] = Math.max(maxLengthArr[key], dep[key].length);
});
});
// Depends on maxLengthArr
const addPadding = function (dep) {
return function (key) {
return `${dep[key]}${' '.repeat(maxLengthArr[key] - dep[key].length)}`;
};
};
const colorizeName = function (_ref3) {
let current = _ref3.current,
wanted = _ref3.wanted;
return current === wanted ? reporter.format.yellow : reporter.format.red;
};
const colorizeDiff = function (from, to) {
const parts = to.split('.');
const fromParts = from.split('.');
const index = parts.findIndex(function (part, i) {
return part !== fromParts[i];
});
const splitIndex = index >= 0 ? index : parts.length;
const colorized = reporter.format.green(parts.slice(splitIndex).join('.'));
return parts.slice(0, splitIndex).concat(colorized).join('.');
};
const makeRow = function (dep) {
const padding = addPadding(dep);
const name = colorizeName(dep)(padding('name'));
const current = reporter.format.blue(padding('current'));
const latest = colorizeDiff(dep.current, padding('latest'));
const url = reporter.format.cyan(dep.url);
return `${name} ${current} ❯ ${latest} ${url}`;
};
const groupedDeps = deps.reduce(function (acc, dep) {
const hint = dep.hint,
name = dep.name,
latest = dep.latest;
const key = getNameFromHint(hint);
const xs = acc[key] || [];
acc[key] = xs.concat({
name: makeRow(dep),
value: dep,
short: `${name}@${latest}`
});
return acc;
}, {});
const flatten = function (xs) {
return xs.reduce(function (ys, y) {
return ys.concat(Array.isArray(y) ? flatten(y) : y);
}, []);
};
const choices = Object.keys(groupedDeps).map(function (key) {
return [new (_inquirer || _load_inquirer()).default.Separator(reporter.format.bold.underline.green(key)), groupedDeps[key], new (_inquirer || _load_inquirer()).default.Separator(' ')];
});
const answers = yield prompt(flatten(choices));
const getName = function (_ref4) {
let name = _ref4.name;
return name;
};
const isHint = function (x) {
return function (_ref5) {
let hint = _ref5.hint;
return hint === x;
};
};
yield [null, 'dev', 'optional', 'peer'].reduce((() => {
var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (promise, hint) {
// Wait for previous promise to resolve
yield promise;
// Reset dependency flags
flags.dev = hint === 'dev';
flags.peer = hint === 'peer';
flags.optional = hint === 'optional';
const deps = answers.filter(isHint(hint)).map(getName);
if (deps.length) {
reporter.info(reporter.lang('updateInstalling', getNameFromHint(hint)));
const add = new (_add || _load_add()).Add(deps, flags, config, reporter, lockfile);
return yield add.init();
}
return Promise.resolve();
});
return function (_x6, _x7) {
return _ref6.apply(this, arguments);
};
})(), Promise.resolve());
});
return function run(_x2, _x3, _x4, _x5) {
return _ref2.apply(this, arguments);
};
})();
exports.setFlags = setFlags;
var _inquirer;
function _load_inquirer() {
return _inquirer = _interopRequireDefault(require('inquirer'));
}
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('../../package-request.js'));
}
var _add;
function _load_add() {
return _add = require('./add.js');
}
var _install;
function _load_install() {
return _install = require('./install.js');
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const tty = require('tty');
const requireLockfile = exports.requireLockfile = true;
function setFlags(commander) {
commander.usage('upgrade-interactive');
commander.option('-E, --exact', 'install exact version');
commander.option('-T, --tilde', 'install most recent release with the same minor version');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.requireLockfile = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
const lockfile = args.length ? yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd, reporter) : new (_wrapper || _load_wrapper()).default();
const manifest = (yield config.readRootManifest()) || {};
const dependencies = manifest.dependencies || {};
const addArgs = args.map(function (dependency) {
const remoteSource = dependencies[dependency];
if (remoteSource && (_packageRequest || _load_packageRequest()).default.getExoticResolver(remoteSource)) {
return remoteSource;
}
return dependency;
});
const addFlags = Object.assign({}, flags, { force: true });
const install = new (_add || _load_add()).Add(addArgs, addFlags, config, reporter, lockfile);
yield install.init();
});
return function run(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
exports.setFlags = setFlags;
var _add;
function _load_add() {
return _add = require('./add.js');
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('../../package-request.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function setFlags(commander) {
// TODO: support some flags that install command has
commander.usage('upgrade [flags]');
}
const requireLockfile = exports.requireLockfile = true;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.setVersion = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let setVersion = exports.setVersion = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args, required) {
let runLifecycle = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (lifecycle) {
if (scripts[lifecycle]) {
return yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execCommand)(lifecycle, config, scripts[lifecycle], config.cwd);
}
return Promise.resolve();
});
return function runLifecycle(_x6) {
return _ref2.apply(this, arguments);
};
})();
const pkg = yield config.readRootManifest();
const pkgLoc = pkg._loc;
const scripts = (0, (_map || _load_map()).default)();
let newVersion = flags.newVersion;
invariant(pkgLoc, 'expected package location');
if (args.length && !newVersion) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidVersionArgument', NEW_VERSION_FLAG));
}
if (pkg.scripts) {
// inherit `scripts` from manifest
Object.assign(scripts, pkg.scripts);
}
// get old version
let oldVersion = pkg.version;
if (oldVersion) {
reporter.info(`${reporter.lang('currentVersion')}: ${oldVersion}`);
} else {
oldVersion = '0.0.0';
}
// get new version
if (newVersion && !isValidNewVersion(oldVersion, newVersion, config.looseSemver)) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidVersion'));
}
// wasn't passed a version arg so ask interactively
while (!newVersion) {
newVersion = yield reporter.question(reporter.lang('newVersion'));
if (!required && !newVersion) {
return function () {
return Promise.resolve();
};
}
if (isValidNewVersion(oldVersion, newVersion, config.looseSemver)) {
break;
} else {
newVersion = null;
reporter.error(reporter.lang('invalidSemver'));
}
}
if (newVersion) {
newVersion = semver.inc(oldVersion, newVersion, config.looseSemver) || newVersion;
}
invariant(newVersion, 'expected new version');
if (newVersion === pkg.version) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('publishSame'));
}
yield runLifecycle('preversion');
// update version
reporter.info(`${reporter.lang('newVersion')}: ${newVersion}`);
pkg.version = newVersion;
// update versions in manifests
const manifests = yield config.getRootManifests();
for (const registryName of (_index || _load_index()).registryNames) {
const manifest = manifests[registryName];
if (manifest.exists) {
manifest.object.version = newVersion;
}
}
yield config.saveRootManifests(manifests);
// check if committing the new version to git is overriden
if (!flags.gitTagVersion || !config.getOption('version-git-tag')) {
// Don't tag the version in Git
return function () {
return Promise.resolve();
};
}
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
invariant(newVersion, 'expected version');
// add git commit and tag
let isGit = false;
const parts = config.cwd.split(path.sep);
while (parts.length) {
isGit = yield (_fs || _load_fs()).exists(path.join(parts.join(path.sep), '.git'));
if (isGit) {
break;
} else {
parts.pop();
}
}
yield runLifecycle('version');
if (isGit) {
const message = (flags.message || String(config.getOption('version-git-message'))).replace(/%s/g, newVersion);
const sign = Boolean(config.getOption('version-sign-git-tag'));
const flag = sign ? '-sm' : '-am';
const prefix = String(config.getOption('version-tag-prefix'));
// add manifest
yield (0, (_child || _load_child()).spawn)('git', ['add', pkgLoc]);
// create git commit
yield (0, (_child || _load_child()).spawn)('git', ['commit', '-m', message]);
// create git tag
yield (0, (_child || _load_child()).spawn)('git', ['tag', `${prefix}${newVersion}`, flag, message]);
}
yield runLifecycle('postversion');
});
});
return function setVersion(_x, _x2, _x3, _x4, _x5) {
return _ref.apply(this, arguments);
};
})();
let run = exports.run = (() => {
var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
const commit = yield setVersion(config, reporter, flags, args, true);
yield commit();
});
return function run(_x7, _x8, _x9, _x10) {
return _ref4.apply(this, arguments);
};
})();
exports.setFlags = setFlags;
var _index;
function _load_index() {
return _index = require('../../registries/index.js');
}
var _executeLifecycleScript;
function _load_executeLifecycleScript() {
return _executeLifecycleScript = require('../../util/execute-lifecycle-script.js');
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _child;
function _load_child() {
return _child = require('../../util/child.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('../../util/map.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const semver = require('semver');
const path = require('path');
const NEW_VERSION_FLAG = '--new-version [version]';
function isValidNewVersion(oldVersion, newVersion, looseSemver) {
return !!(semver.valid(newVersion, looseSemver) || semver.inc(oldVersion, newVersion, looseSemver));
}
function setFlags(commander) {
commander.option(NEW_VERSION_FLAG, 'new version');
commander.option('--message [message]', 'message');
commander.option('--no-git-tag-version', 'no git tag version');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let run = exports.run = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
const versions = { yarn: YARN_VERSION };
const pkg = yield config.maybeReadManifest(config.cwd);
if (pkg && pkg.name && pkg.version) {
versions[pkg.name] = pkg.version;
}
Object.assign(versions, process.versions);
reporter.inspect(versions);
});
return function run(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const YARN_VERSION = require('../../../package.json').version;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = exports.requireLockfile = undefined;
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let cleanQuery = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, query) {
// if a location was passed then turn it into a hash query
if (path.isAbsolute(query) && (yield (_fs || _load_fs()).exists(query))) {
// absolute path
query = path.relative(config.cwd, query);
}
// remove references to node_modules with hashes
query = query.replace(/([\\/]|^)node_modules[\\/]/g, '#');
// remove trailing hashes
query = query.replace(/^#+/g, '');
// remove trailing paths from each part of the query, skip second part of path for scoped packages
let queryParts = query.split('#');
queryParts = queryParts.map(function (part) {
let parts = part.split(/[\\/]/g);
if (part[0] === '@') {
parts = parts.slice(0, 2);
} else {
parts = parts.slice(0, 1);
}
return parts.join('/');
});
query = queryParts.join('#');
return query;
});
return function cleanQuery(_x, _x2) {
return _ref.apply(this, arguments);
};
})();
let getPackageSize = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (tuple) {
var _tuple = (0, (_slicedToArray2 || _load_slicedToArray()).default)(tuple, 1);
const loc = _tuple[0];
const files = yield (_fs || _load_fs()).walk(loc, null, new Set([(_constants || _load_constants()).METADATA_FILENAME, (_constants || _load_constants()).TARBALL_FILENAME]));
const sizes = yield Promise.all(files.map(function (walkFile) {
return (_fs || _load_fs()).getFileSizeOnDisk(walkFile.absolute);
}));
return sum(sizes);
});
return function getPackageSize(_x3) {
return _ref2.apply(this, arguments);
};
})();
let run = exports.run = (() => {
var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
if (!args.length) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('missingWhyDependency'));
}
if (args.length > 1) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('tooManyArguments', 1));
}
const query = yield cleanQuery(config, args[0]);
reporter.step(1, 4, reporter.lang('whyStart', args[0]), emoji.get('thinking_face'));
// init
reporter.step(2, 4, reporter.lang('whyInitGraph'), emoji.get('truck'));
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd, reporter);
const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile);
var _ref7 = yield install.fetchRequestFromCwd();
const depRequests = _ref7.requests,
patterns = _ref7.patterns;
yield install.resolver.init(depRequests, install.flags.flat);
const hoisted = yield install.linker.getFlatHoistedTree(patterns);
// finding
reporter.step(3, 4, reporter.lang('whyFinding'), emoji.get('mag'));
let match;
for (const _ref8 of hoisted) {
var _ref9 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref8, 2);
const loc = _ref9[0];
const info = _ref9[1];
if (info.key === query || info.previousKeys.indexOf(query) >= 0) {
match = [loc, info];
break;
}
}
if (!match) {
reporter.error(reporter.lang('whyUnknownMatch'));
return;
}
var _match = match,
_match2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_match, 2);
const matchInfo = _match2[1];
const matchRef = matchInfo.pkg._reference;
invariant(matchRef, 'expected reference');
const matchPatterns = matchRef.patterns;
const matchRequests = matchRef.requests;
const reasons = [];
// reason: dependency of these modules
for (const request of matchRequests) {
const parentRequest = request.parentRequest;
if (!parentRequest) {
continue;
}
const dependent = install.resolver.getResolvedPattern(parentRequest.pattern);
if (!dependent) {
continue;
}
const chain = [];
let delegator = parentRequest;
do {
chain.push(install.resolver.getStrictResolvedPattern(delegator.pattern).name);
} while (delegator = delegator.parentRequest);
reasons.push({
type: 'whyDependedOn',
typeSimple: 'whyDependedOnSimple',
value: chain.reverse().join('#')
});
}
// reason: exists in manifest
let rootType;
for (const pattern of matchPatterns) {
rootType = install.rootPatternsToOrigin[pattern];
if (rootType) {
reasons.push({
type: 'whySpecified',
typeSimple: 'whySpecifiedSimple',
value: rootType
});
}
}
// reason: this is hoisted from these modules
for (const pattern of matchInfo.previousKeys) {
if (pattern !== matchInfo.key) {
reasons.push({
type: 'whyHoistedFrom',
typeSimple: 'whyHoistedFromSimple',
value: pattern
});
}
}
// package sizes
reporter.step(4, 4, reporter.lang('whyCalculating'), emoji.get('aerial_tramway'));
let packageSize = 0;
let directSizes = [];
let transitiveSizes = [];
try {
packageSize = yield getPackageSize(match);
} catch (e) {}
const dependencies = Array.from(collect(hoisted, new Set(), match));
const transitiveDependencies = Array.from(collect(hoisted, new Set(), match, { recursive: true }));
try {
directSizes = yield Promise.all(dependencies.map(getPackageSize));
transitiveSizes = yield Promise.all(transitiveDependencies.map(getPackageSize));
} catch (e) {}
const transitiveKeys = new Set(transitiveDependencies.map(function (_ref10) {
var _ref11 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref10, 2);
let info = _ref11[1];
return info.key;
}));
const sharedDependencies = getSharedDependencies(hoisted, transitiveKeys);
//
// reason: hoisted
if (query === matchInfo.originalKey) {
reporter.info(reporter.lang('whyHoistedTo', matchInfo.key));
}
if (reasons.length === 1) {
reporter.info(reporter.lang(reasons[0].typeSimple, reasons[0].value));
} else if (reasons.length > 1) {
reporter.info(reporter.lang('whyReasons'));
reporter.list('reasons', reasons.map(function (reason) {
return reporter.lang(reason.type, reason.value);
}));
} else {
reporter.error(reporter.lang('whyWhoKnows'));
}
if (packageSize) {
// stats: file size of this dependency without any dependencies
reporter.info(reporter.lang('whyDiskSizeWithout', bytes(packageSize)));
// stats: file size of this dependency including dependencies that aren't shared
reporter.info(reporter.lang('whyDiskSizeUnique', bytes(packageSize + sum(directSizes))));
// stats: file size of this dependency including dependencies
reporter.info(reporter.lang('whyDiskSizeTransitive', bytes(packageSize + sum(transitiveSizes))));
// stats: shared transitive dependencies
reporter.info(reporter.lang('whySharedDependencies', sharedDependencies.size));
}
});
return function run(_x5, _x6, _x7, _x8) {
return _ref6.apply(this, arguments);
};
})();
var _install;
function _load_install() {
return _install = require('./install.js');
}
var _constants;
function _load_constants() {
return _constants = require('../../constants.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const requireLockfile = exports.requireLockfile = true;
const invariant = require('invariant');
const bytes = require('bytes');
const emoji = require('node-emoji');
const path = require('path');
function sum(array) {
return array.length ? array.reduce((a, b) => a + b, 0) : 0;
}
function collect(hoistManifests, allDependencies, dependency) {
var _ref3 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { recursive: false };
let recursive = _ref3.recursive;
var _dependency = (0, (_slicedToArray2 || _load_slicedToArray()).default)(dependency, 2);
const depInfo = _dependency[1];
const deps = depInfo.pkg.dependencies;
if (!deps) {
return allDependencies;
}
const dependencyKeys = new Set(Object.keys(deps));
const directDependencies = [];
for (const dep of hoistManifests) {
var _dep = (0, (_slicedToArray2 || _load_slicedToArray()).default)(dep, 2);
const info = _dep[1];
if (!allDependencies.has(dep) && dependencyKeys.has(info.key)) {
allDependencies.add(dep);
directDependencies.push(dep);
}
}
if (recursive) {
directDependencies.forEach(dependency => collect(hoistManifests, allDependencies, dependency, { recursive: true }));
}
return allDependencies;
}
function getSharedDependencies(hoistManifests, transitiveKeys) {
const sharedDependencies = new Set();
for (const _ref4 of hoistManifests) {
var _ref5 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref4, 2);
const info = _ref5[1];
if (!transitiveKeys.has(info.key) && info.pkg.dependencies) {
Object.keys(info.pkg.dependencies).forEach(dependency => {
if (transitiveKeys.has(dependency) && !sharedDependencies.has(dependency)) {
sharedDependencies.add(dependency);
}
});
}
}
return sharedDependencies;
}
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| base-fetcher.js | 78.57% | (33 / 42) | 63.64% | (14 / 22) | 80% | (8 / 10) | 93.75% | (30 / 32) | |
| copy-fetcher.js | 44.44% | (12 / 27) | 25% | (5 / 20) | 28.57% | (2 / 7) | 64.71% | (11 / 17) | |
| git-fetcher.js | 28.05% | (23 / 82) | 9.8% | (5 / 51) | 12.5% | (2 / 16) | 30.56% | (22 / 72) | |
| index.js | 100% | (20 / 20) | 91.67% | (11 / 12) | 100% | (5 / 5) | 100% | (19 / 19) | |
| tarball-fetcher.js | 58.33% | (77 / 132) | 34.09% | (30 / 88) | 59.09% | (13 / 22) | 60.66% | (74 / 122) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | 1 1 1 1 1 1 1 1 1 1 2 1 1 173 173 173 173 173 173 173 7 7 7 7 7 7 7 7 7 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../util/fs.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint no-unused-vars: 0 */
const path = require('path');
class BaseFetcher {
constructor(dest, remote, config) {
this.reporter = config.reporter;
this.reference = remote.reference;
this.registry = remote.registry;
this.hash = remote.hash;
this.remote = remote;
this.config = config;
this.dest = dest;
}
getResolvedFromCached(hash) {
// fetcher subclasses may use this to perform actions such as copying over a cached tarball to the offline
// mirror etc
return Promise.resolve();
}
_fetch() {
return Promise.reject(new Error('Not implemented'));
}
fetch() {
var _this = this;
const dest = this.dest;
return (_fs || _load_fs()).lockQueue.push(dest, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield (_fs || _load_fs()).mkdirp(dest);
// fetch package and get the hash
var _ref2 = yield _this._fetch();
const hash = _ref2.hash,
resolved = _ref2.resolved;
// load the new normalized manifest
const pkg = yield _this.config.readManifest(dest, _this.registry);
yield (_fs || _load_fs()).writeFile(path.join(dest, (_constants || _load_constants()).METADATA_FILENAME), JSON.stringify({
artifacts: [],
remote: _this.remote,
registry: _this.registry,
hash
}, null, ' '));
return {
resolved,
hash,
dest,
package: pkg,
cached: false
};
}));
}
}
exports.default = BaseFetcher;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _baseFetcher;
function _load_baseFetcher() {
return _baseFetcher = _interopRequireDefault(require('./base-fetcher.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class CopyFetcher extends (_baseFetcher || _load_baseFetcher()).default {
_fetch() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield (_fs || _load_fs()).copy(_this.reference, _this.dest, _this.reporter);
return {
hash: _this.hash || '',
resolved: null
};
})();
}
}
exports.default = CopyFetcher;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _baseFetcher;
function _load_baseFetcher() {
return _baseFetcher = _interopRequireDefault(require('./base-fetcher.js'));
}
var _git;
function _load_git() {
return _git = _interopRequireDefault(require('../util/git.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../util/fs.js'));
}
var _crypto;
function _load_crypto() {
return _crypto = _interopRequireWildcard(require('../util/crypto.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const tar = require('tar');
const url = require('url');
const path = require('path');
const fs = require('fs');
const invariant = require('invariant');
class GitFetcher extends (_baseFetcher || _load_baseFetcher()).default {
_fetch() {
var _url$parse = url.parse(this.reference);
const protocol = _url$parse.protocol,
pathname = _url$parse.pathname;
if (protocol === null && typeof pathname === 'string') {
return this.fetchFromLocal(pathname);
} else {
return this.fetchFromExternal();
}
}
fetchFromLocal(pathname) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const ref = _this.reference,
config = _this.config;
const offlineMirrorPath = config.getOfflineMirrorPath() || '';
const localTarball = path.resolve(offlineMirrorPath, ref);
const reporter = config.reporter;
if (!(yield (_fs || _load_fs()).exists(localTarball))) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('tarballNotInNetworkOrCache', ref, localTarball));
}
return new Promise(function (resolve, reject) {
const untarStream = tar.Extract({ path: _this.dest });
const hashStream = new (_crypto || _load_crypto()).HashStream();
const cachedStream = fs.createReadStream(localTarball);
cachedStream.pipe(hashStream).pipe(untarStream).on('end', function () {
const expectHash = _this.hash;
const actualHash = hashStream.getHash();
if (!expectHash || expectHash === actualHash) {
resolve({
hash: actualHash,
resolved: `${pathname}#${actualHash}`
});
} else {
reject(new (_errors || _load_errors()).SecurityError(reporter.lang('fetchBadHash', expectHash, actualHash)));
}
}).on('error', function (err) {
reject(new (_errors || _load_errors()).MessageError(reporter.lang('fetchErrorCorrupt', err.message, localTarball)));
});
});
})();
}
fetchFromExternal() {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const commit = _this2.hash;
invariant(commit, 'Commit hash required');
const git = new (_git || _load_git()).default(_this2.config, _this2.reference, commit);
yield git.init();
yield git.clone(_this2.dest);
// Get the tarball filename from the url
var _url$parse2 = url.parse(_this2.reference);
const pathname = _url$parse2.pathname;
let tarballFilename;
if (pathname == null) {
tarballFilename = _this2.reference;
} else {
tarballFilename = path.basename(pathname);
}
let tarballInMirrorPath = _this2.config.getOfflineMirrorPath(tarballFilename);
const mirrorRootPath = _this2.config.getOfflineMirrorPath();
if (tarballInMirrorPath && _this2.hash && mirrorRootPath) {
tarballInMirrorPath = `${tarballInMirrorPath}-${commit}`;
const hash = yield git.archive(tarballInMirrorPath);
const relativeMirrorPath = path.relative(mirrorRootPath, tarballInMirrorPath);
return {
hash: commit,
resolved: relativeMirrorPath ? `${relativeMirrorPath}#${hash}` : null
};
}
return {
hash: commit,
resolved: null
};
})();
}
}
exports.default = GitFetcher;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.tarball = exports.git = exports.copy = exports.base = undefined;
var _baseFetcher;
function _load_baseFetcher() {
return _baseFetcher = _interopRequireDefault(require('./base-fetcher.js'));
}
var _copyFetcher;
function _load_copyFetcher() {
return _copyFetcher = _interopRequireDefault(require('./copy-fetcher.js'));
}
var _gitFetcher;
function _load_gitFetcher() {
return _gitFetcher = _interopRequireDefault(require('./git-fetcher.js'));
}
var _tarballFetcher;
function _load_tarballFetcher() {
return _tarballFetcher = _interopRequireDefault(require('./tarball-fetcher.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.base = (_baseFetcher || _load_baseFetcher()).default;
exports.copy = (_copyFetcher || _load_copyFetcher()).default;
exports.git = (_gitFetcher || _load_gitFetcher()).default;
exports.tarball = (_tarballFetcher || _load_tarballFetcher()).default;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 1 166 166 166 166 166 173 173 173 173 173 173 173 7 7 7 7 2854 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LocalTarballFetcher = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _http;
function _load_http() {
return _http = _interopRequireDefault(require('http'));
}
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _stream;
function _load_stream() {
return _stream = require('../util/stream.js');
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _crypto;
function _load_crypto() {
return _crypto = _interopRequireWildcard(require('../util/crypto.js'));
}
var _baseFetcher;
function _load_baseFetcher() {
return _baseFetcher = _interopRequireDefault(require('./base-fetcher.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../util/fs.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const path = require('path');
const tar = require('tar');
const url = require('url');
const fs = require('fs');
class TarballFetcher extends (_baseFetcher || _load_baseFetcher()).default {
getResolvedFromCached(hash) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const mirrorPath = _this.getMirrorPath();
Eif (mirrorPath == null) {
// no mirror
return null;
}
const tarballLoc = path.join(_this.dest, (_constants || _load_constants()).TARBALL_FILENAME);
if (!(yield (_fs || _load_fs()).exists(tarballLoc))) {
// no tarball located in the cache
return null;
}
// copy the file over
if (!(yield (_fs || _load_fs()).exists(mirrorPath))) {
yield (_fs || _load_fs()).copy(tarballLoc, mirrorPath, _this.reporter);
}
const relativeMirrorPath = _this.getRelativeMirrorPath(mirrorPath);
invariant(relativeMirrorPath != null, 'Missing offline mirror path');
return `${relativeMirrorPath}#${hash}`;
})();
}
getMirrorPath() {
var _url$parse = url.parse(this.reference);
const pathname = _url$parse.pathname;
Iif (pathname == null) {
return this.config.getOfflineMirrorPath();
}
let packageFilename = path.basename(pathname);
// handle scoped packages
const pathParts = pathname.slice(1).split('/');
Iif (pathParts[0][0] === '@') {
// scoped npm package
packageFilename = `${pathParts[0]}-${packageFilename}`;
}
return this.config.getOfflineMirrorPath(packageFilename);
}
getRelativeMirrorPath(mirrorPath) {
const offlineMirrorPath = this.config.getOfflineMirrorPath();
if (offlineMirrorPath == null) {
return null;
}
return path.relative(offlineMirrorPath, mirrorPath);
}
createExtractor(mirrorPath, resolve, reject) {
const validateStream = new (_crypto || _load_crypto()).HashStream();
const extractorStream = new (_stream || _load_stream()).UnpackStream();
const untarStream = tar.Extract({ path: this.dest, strip: 1 });
extractorStream.pipe(untarStream).on('error', reject).on('entry', entry => {
Iif ((_constants || _load_constants()).ROOT_USER) {
entry.props.uid = entry.uid = 0;
entry.props.gid = entry.gid = 0;
}
}).on('end', () => {
const expectHash = this.hash;
const actualHash = validateStream.getHash();
Eif (!expectHash || expectHash === actualHash) {
resolve({
hash: actualHash,
resolved: mirrorPath ? `${mirrorPath}#${actualHash}` : null
});
} else {
reject(new (_errors || _load_errors()).SecurityError(this.config.reporter.lang('fetchBadHash', expectHash, actualHash)));
}
});
return { validateStream, extractorStream };
}
fetchFromLocal(pathname) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const ref = _this2.reference,
config = _this2.config;
const reporter = config.reporter;
// path to the local tarball
let localTarball;
let isOfflineTarball = false;
const relativeFileLoc = pathname ? path.join(config.cwd, pathname) : null;
if (relativeFileLoc && (yield (_fs || _load_fs()).exists(relativeFileLoc))) {
// this is a reference to a file relative to the cwd
localTarball = relativeFileLoc;
} else {
// generate a offline cache location
const offlineMirrorPath = config.getOfflineMirrorPath() || '';
localTarball = path.resolve(offlineMirrorPath, ref);
isOfflineTarball = true;
}
if (!(yield (_fs || _load_fs()).exists(localTarball))) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('tarballNotInNetworkOrCache', ref, localTarball));
}
return new Promise(function (resolve, reject) {
var _createExtractor = _this2.createExtractor(null, resolve, reject);
const validateStream = _createExtractor.validateStream,
extractorStream = _createExtractor.extractorStream;
const cachedStream = fs.createReadStream(localTarball);
cachedStream.pipe(validateStream).pipe(extractorStream).on('error', function (err) {
let msg = 'errorDecompressingTarball';
if (isOfflineTarball) {
msg = 'fetchErrorCorrupt';
}
reject(new (_errors || _load_errors()).MessageError(reporter.lang(msg, err.message, localTarball)));
});
});
})();
}
fetchFromExternal() {
const ref = this.reference;
const registry = this.config.registries[this.registry];
return registry.request(ref, {
headers: {
'Accept-Encoding': 'gzip',
'Accept': 'application/octet-stream'
},
buffer: true,
process: (req, resolve, reject) => {
const reporter = this.config.reporter;
// should we save this to the offline cache?
const mirrorPath = this.getMirrorPath();
const tarballStorePath = path.join(this.dest, (_constants || _load_constants()).TARBALL_FILENAME);
const overwriteResolved = mirrorPath ? this.getRelativeMirrorPath(mirrorPath) : null;
//
var _createExtractor2 = this.createExtractor(overwriteResolved, resolve, reject);
const validateStream = _createExtractor2.validateStream,
extractorStream = _createExtractor2.extractorStream;
const handleRequestError = res => {
Iif (res.statusCode >= 400) {
// $FlowFixMe
const statusDescription = (_http || _load_http()).default.STATUS_CODES[res.statusCode];
reject(new Error(reporter.lang('requestFailed', `${res.statusCode} ${statusDescription}`)));
}
};
req.on('response', handleRequestError);
req.pipe(validateStream);
validateStream.pipe(fs.createWriteStream(tarballStorePath)).on('error', reject);
validateStream.pipe(extractorStream).on('error', reject);
Iif (mirrorPath) {
validateStream.pipe(fs.createWriteStream(mirrorPath)).on('error', reject);
}
}
});
}
_fetch() {
var _url$parse2 = url.parse(this.reference);
const protocol = _url$parse2.protocol,
pathname = _url$parse2.pathname;
Iif (protocol === null && typeof pathname === 'string') {
return this.fetchFromLocal(pathname);
} else {
return this.fetchFromExternal();
}
}
}
exports.default = TarballFetcher;
class LocalTarballFetcher extends TarballFetcher {
_fetch() {
return this.fetchFromLocal(this.reference);
}
}
exports.LocalTarballFetcher = LocalTarballFetcher;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| stringify.js | 94% | (47 / 50) | 87.23% | (41 / 47) | 100% | (7 / 7) | 94% | (47 / 50) | |
| wrapper.js | 71.84% | (74 / 103) | 47.37% | (36 / 76) | 71.43% | (15 / 21) | 76.34% | (71 / 93) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | 1 1 1 1 1 1 1 1 1 1419 1 1419 574 845 1 1 3063 1038 2025 1 252 252 252 252 252 252 1809 1809 1809 988 821 821 251 17757 17757 28 821 821 570 251 251 821 252 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = stringify;
var _misc;
function _load_misc() {
return _misc = require('../util/misc.js');
}
var _constants;
function _load_constants() {
return _constants = require('../constants.js');
}
function shouldWrapKey(str) {
return str.indexOf('true') === 0 || str.indexOf('false') === 0 || /[:\s\n\\",\[\]]/g.test(str) || /^[0-9]/g.test(str) || !/^[a-zA-Z]/g.test(str);
}
function maybeWrap(str) {
if (typeof str === 'boolean' || typeof str === 'number' || shouldWrapKey(str)) {
return JSON.stringify(str);
} else {
return str;
}
}
const priorities = {
name: 1,
version: 2,
uid: 3,
resolved: 4,
registry: 5,
dependencies: 6
};
function priorityThenAlphaSort(a, b) {
if (priorities[a] || priorities[b]) {
return (priorities[a] || 100) > (priorities[b] || 100) ? 1 : -1;
} else {
return (0, (_misc || _load_misc()).sortAlpha)(a, b);
}
}
function _stringify(obj, options) {
Iif (typeof obj !== 'object') {
throw new TypeError();
}
const indent = options.indent;
const lines = [];
// Sorting order needs to be consistent between runs, we run native sort by name because there are no
// problems with it being unstable because there are no to keys the same
// However priorities can be duplicated and native sort can shuffle things from run to run
const keys = Object.keys(obj).sort(priorityThenAlphaSort);
let addedKeys = [];
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const val = obj[key];
if (val == null || addedKeys.indexOf(key) >= 0) {
continue;
}
//
const valKeys = [key];
// get all keys that have the same value equality, we only want this for objects
if (typeof val === 'object') {
for (let j = i + 1; j < keys.length; j++) {
const key = keys[j];
if (val === obj[key]) {
valKeys.push(key);
}
}
}
//
const keyLine = valKeys.sort((_misc || _load_misc()).sortAlpha).map(maybeWrap).join(', ');
if (typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number') {
lines.push(`${keyLine} ${maybeWrap(val)}`);
} else Eif (typeof val === 'object') {
lines.push(`${keyLine}:\n${_stringify(val, { indent: indent + ' ' })}` + (options.topLevel ? '\n' : ''));
} else {
throw new TypeError();
}
addedKeys = addedKeys.concat(valKeys);
}
return indent + lines.join(`\n${indent}`);
}
function stringify(obj, noHeader) {
const val = _stringify(obj, {
indent: '',
topLevel: true
});
Iif (noHeader) {
return val;
}
return ['# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.', `# yarn lockfile v${(_constants || _load_constants()).LOCKFILE_VERSION}`, '\n', val].join('\n');
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 201 1 519 1 173 173 1 1 1 1 1 1 1 1 1 1 1 607 607 607 1 1 1 1 201 201 201 201 201 201 28 28 28 173 173 173 173 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.stringify = exports.parse = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _parse;
function _load_parse() {
return _parse = require('./parse');
}
Object.defineProperty(exports, 'parse', {
enumerable: true,
get: function () {
return _interopRequireDefault(_parse || _load_parse()).default;
}
});
var _stringify;
function _load_stringify() {
return _stringify = require('./stringify');
}
Object.defineProperty(exports, 'stringify', {
enumerable: true,
get: function () {
return _interopRequireDefault(_stringify || _load_stringify()).default;
}
});
exports.implodeEntry = implodeEntry;
exports.explodeEntry = explodeEntry;
var _misc;
function _load_misc() {
return _misc = require('../util/misc.js');
}
var _packageRequest;
function _load_packageRequest() {
return _packageRequest = _interopRequireDefault(require('../package-request.js'));
}
var _parse2;
function _load_parse2() {
return _parse2 = _interopRequireDefault(require('./parse.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../util/fs.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const path = require('path');
function getName(pattern) {
return (_packageRequest || _load_packageRequest()).default.normalizePattern(pattern).name;
}
function blankObjectUndefined(obj) {
return obj && Object.keys(obj).length ? obj : undefined;
}
function implodeEntry(pattern, obj) {
const inferredName = getName(pattern);
return {
name: inferredName === obj.name ? undefined : obj.name,
version: obj.version,
uid: obj.uid === obj.version ? undefined : obj.uid,
resolved: obj.resolved,
registry: obj.registry === 'npm' ? undefined : obj.registry,
dependencies: blankObjectUndefined(obj.dependencies),
optionalDependencies: blankObjectUndefined(obj.optionalDependencies),
permissions: blankObjectUndefined(obj.permissions)
};
}
function explodeEntry(pattern, obj) {
obj.optionalDependencies = obj.optionalDependencies || {};
obj.dependencies = obj.dependencies || {};
obj.uid = obj.uid || obj.version;
obj.permissions = obj.permissions || {};
obj.registry = obj.registry || 'npm';
obj.name = obj.name || getName(pattern);
return obj;
}
class Lockfile {
constructor(cache, source) {
this.source = source || '';
this.cache = cache;
}
// source string if the `cache` was parsed
static fromDirectory(dir, reporter) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// read the manifest in this directory
const lockfileLoc = path.join(dir, (_constants || _load_constants()).LOCKFILE_FILENAME);
let lockfile;
let rawLockfile = '';
Iif (yield (_fs || _load_fs()).exists(lockfileLoc)) {
rawLockfile = yield (_fs || _load_fs()).readFile(lockfileLoc);
lockfile = (0, (_parse2 || _load_parse2()).default)(rawLockfile, lockfileLoc);
} else {
Eif (reporter) {
reporter.info(reporter.lang('noLockfileFound'));
}
}
return new Lockfile(lockfile, rawLockfile);
})();
}
getLocked(pattern) {
const cache = this.cache;
Eif (!cache) {
return undefined;
}
const shrunk = pattern in cache && cache[pattern];
if (typeof shrunk === 'string') {
return this.getLocked(shrunk);
} else if (shrunk) {
explodeEntry(pattern, shrunk);
return shrunk;
}
return undefined;
}
getLockfile(patterns) {
const lockfile = {};
const seen = new Map();
// order by name so that lockfile manifest is assigned to the first dependency with this manifest
// the others that have the same remote.resolved will just refer to the first
// ordering allows for consistency in lockfile when it is serialized
const sortedPatternsKeys = Object.keys(patterns).sort((_misc || _load_misc()).sortAlpha);
for (const pattern of sortedPatternsKeys) {
const pkg = patterns[pattern];
const remote = pkg._remote,
ref = pkg._reference;
invariant(ref, 'Package is missing a reference');
invariant(remote, 'Package is missing a remote');
const seenPattern = remote.resolved && seen.get(remote.resolved);
if (seenPattern) {
// no point in duplicating it
lockfile[pattern] = seenPattern;
// if we're relying on our name being inferred and two of the patterns have
// different inferred names then we need to set it
Iif (!seenPattern.name && getName(pattern) !== pkg.name) {
seenPattern.name = pkg.name;
}
continue;
}
const obj = implodeEntry(pattern, {
name: pkg.name,
version: pkg.version,
uid: pkg._uid,
resolved: remote.resolved,
registry: remote.registry,
dependencies: pkg.dependencies,
peerDependencies: pkg.peerDependencies,
optionalDependencies: pkg.optionalDependencies,
permissions: ref.permissions
});
lockfile[pattern] = obj;
Eif (remote.resolved) {
seen.set(remote.resolved, obj);
}
}
return lockfile;
}
}
exports.default = Lockfile;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| base-registry.js | 85.71% | (48 / 56) | 66.67% | (16 / 24) | 64.71% | (11 / 17) | 85.45% | (47 / 55) | |
| index.js | 100% | (12 / 12) | 87.5% | (7 / 8) | 100% | (3 / 3) | 100% | (11 / 11) | |
| npm-registry.js | 67.67% | (90 / 133) | 53% | (53 / 100) | 79.17% | (19 / 24) | 70.49% | (86 / 122) | |
| yarn-registry.js | 56.41% | (44 / 78) | 34.09% | (15 / 44) | 53.33% | (8 / 15) | 63.24% | (43 / 68) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 1238 7 7 742 7 742 2 2 2 2 2 2 4 2 110 12 98 98 3 807 807 701 106 106 106 106 106 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _misc;
function _load_misc() {
return _misc = require('../util/misc.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const objectPath = require('object-path');
const path = require('path');
class BaseRegistry {
constructor(cwd, registries, requestManager) {
this.requestManager = requestManager;
this.registries = registries;
this.config = {};
this.folder = '';
this.token = '';
this.loc = '';
this.cwd = cwd;
}
// the filename to use for package metadata
//
//
//
//
//
// absolute folder name to insert modules
// relative folder name to put these modules
setToken(token) {
this.token = token;
}
getOption(key) {
return this.config[key];
}
getAvailableRegistries() {
const config = this.config;
return Object.keys(config).reduce((registries, option) => {
if (option === 'registry' || option.split(':')[1] === 'registry') {
registries.push(config[option]);
}
return registries;
}, []);
}
loadConfig() {
return Promise.resolve();
}
checkOutdated(config, name, range) {
return Promise.reject(new Error('unimplemented'));
}
saveHomeConfig(config) {
return Promise.reject(new Error('unimplemented'));
}
request(pathname) {
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.requestManager.request((0, (_extends2 || _load_extends()).default)({
url: pathname
}, opts));
}
init() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this.mergeEnv('yarn_');
yield _this.loadConfig();
_this.loc = path.join(_this.cwd, _this.folder);
})();
}
static normalizeConfig(config) {
for (const key in config) {
config[key] = BaseRegistry.normalizeConfigOption(config[key]);
}
return config;
}
static normalizeConfigOption(val) {
if (val === 'true') {
return true;
} else Iif (val === 'false') {
return false;
} else {
return val;
}
}
mergeEnv(prefix) {
// try environment variables
for (let key in process.env) {
key = key.toLowerCase();
// only accept keys prefixed with the prefix
if (key.indexOf(prefix) < 0) {
continue;
}
const val = BaseRegistry.normalizeConfigOption(process.env[key]);
// remove config prefix
key = (0, (_misc || _load_misc()).removePrefix)(key, prefix);
// replace dunders with dots
key = key.replace(/__/g, '.');
// replace underscores with dashes
key = key.replace(/_/g, '-');
// set it via a path
objectPath.set(this.config, key, val);
}
}
}
exports.default = BaseRegistry;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 1 1 1 1 1 1 1 1 2 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.registryNames = exports.registries = undefined;
var _yarnRegistry;
function _load_yarnRegistry() {
return _yarnRegistry = _interopRequireDefault(require('./yarn-registry.js'));
}
var _npmRegistry;
function _load_npmRegistry() {
return _npmRegistry = _interopRequireDefault(require('./npm-registry.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const registries = exports.registries = {
npm: (_npmRegistry || _load_npmRegistry()).default,
yarn: (_yarnRegistry || _load_yarnRegistry()).default
};
const registryNames = exports.registryNames = Object.keys(registries);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 2 2 2 2 2 2 2 199 206 206 206 206 206 206 206 2 2 2 2 2 10 10 2 2 16 16 16 16 2 2 1 1 1 1 2 2 2 2 2 4 2 2 2 206 206 7 7 7 206 206 206 206 412 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../util/fs.js'));
}
var _npmResolver;
function _load_npmResolver() {
return _npmResolver = _interopRequireDefault(require('../resolvers/registries/npm-resolver.js'));
}
var _envReplace;
function _load_envReplace() {
return _envReplace = _interopRequireDefault(require('../util/env-replace.js'));
}
var _baseRegistry;
function _load_baseRegistry() {
return _baseRegistry = _interopRequireDefault(require('./base-registry.js'));
}
var _misc;
function _load_misc() {
return _misc = require('../util/misc');
}
var _isRequestToRegistry;
function _load_isRequestToRegistry() {
return _isRequestToRegistry = _interopRequireDefault(require('./is-request-to-registry.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const userHome = require('../util/user-home-dir').default;
const path = require('path');
const url = require('url');
const ini = require('ini');
const DEFAULT_REGISTRY = 'https://registry.npmjs.org/';
function getGlobalPrefix() {
Iif (process.env.PREFIX) {
return process.env.PREFIX;
} else Iif (process.platform === 'win32') {
// c:\node\node.exe --> prefix=c:\node\
return path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
let prefix = path.dirname(path.dirname(process.execPath));
// destdir only is respected on Unix
Iif (process.env.DESTDIR) {
prefix = path.join(process.env.DESTDIR, prefix);
}
return prefix;
}
}
class NpmRegistry extends (_baseRegistry || _load_baseRegistry()).default {
constructor(cwd, registries, requestManager) {
super(cwd, registries, requestManager);
this.folder = 'node_modules';
}
static escapeName(name) {
// scoped packages contain slashes and the npm registry expects them to be escaped
return name.replace('/', '%2f');
}
request(pathname) {
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const registry = (0, (_misc || _load_misc()).addSuffix)(this.getRegistry(pathname), '/');
const requestUrl = url.resolve(registry, pathname);
const alwaysAuth = this.getScopedOption(registry.replace(/^https?:/, ''), 'always-auth') || this.getOption('always-auth') || (0, (_misc || _load_misc()).removePrefix)(requestUrl, registry)[0] === '@';
const headers = {};
Iif (this.token || alwaysAuth && (0, (_isRequestToRegistry || _load_isRequestToRegistry()).default)(requestUrl, registry)) {
const authorization = this.getAuth(pathname);
if (authorization) {
headers.authorization = authorization;
}
}
return this.requestManager.request({
url: requestUrl,
method: opts.method,
body: opts.body,
auth: opts.auth,
headers,
json: !opts.buffer,
buffer: opts.buffer,
process: opts.process,
gzip: true
});
}
checkOutdated(config, name, range) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const req = yield _this.request(NpmRegistry.escapeName(name));
if (!req) {
throw new Error('couldnt find ' + name);
}
const repository = req.repository,
homepage = req.homepage;
const url = homepage || repository && repository.url || '';
return {
latest: req['dist-tags'].latest,
wanted: (yield (_npmResolver || _load_npmResolver()).default.findVersionInRegistryResponse(config, range, req)).version,
url
};
})();
}
getPossibleConfigLocations(filename) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const possibles = [[false, path.join(_this2.cwd, filename)], [true, _this2.config.userconfig || path.join(userHome, filename)], [false, path.join(getGlobalPrefix(), filename)]];
const foldersFromRootToCwd = _this2.cwd.split(path.sep);
while (foldersFromRootToCwd.length > 1) {
possibles.push([false, path.join(foldersFromRootToCwd.join(path.sep), filename)]);
foldersFromRootToCwd.pop();
}
const actuals = [];
for (const _ref of possibles) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const isHome = _ref2[0];
const loc = _ref2[1];
if (yield (_fs || _load_fs()).exists(loc)) {
actuals.push([isHome, loc, yield (_fs || _load_fs()).readFile(loc)]);
}
}
return actuals;
})();
}
loadConfig() {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// docs: https://docs.npmjs.com/misc/config
_this3.mergeEnv('npm_config_');
for (const _ref3 of yield _this3.getPossibleConfigLocations('.npmrc')) {
var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 3);
const loc = _ref4[1];
const file = _ref4[2];
const config = (_baseRegistry || _load_baseRegistry()).default.normalizeConfig(ini.parse(file));
for (const key in config) {
config[key] = (0, (_envReplace || _load_envReplace()).default)(config[key]);
}
// normalize offline mirror path relative to the current npmrc
const offlineLoc = config['yarn-offline-mirror'];
// don't normalize if we already have a mirror path
Iif (!_this3.config['yarn-offline-mirror'] && offlineLoc) {
const mirrorLoc = config['yarn-offline-mirror'] = path.resolve(path.dirname(loc), offlineLoc);
yield (_fs || _load_fs()).mkdirp(mirrorLoc);
}
_this3.config = Object.assign({}, config, _this3.config);
}
})();
}
getScope(packageName) {
return !packageName || packageName[0] !== '@' ? '' : packageName.split(/\/|%2f/)[0];
}
getRegistry(packageName) {
// Try extracting registry from the url, then scoped registry, and default registry
if (packageName.match(/^https?:/)) {
const availableRegistries = this.getAvailableRegistries();
const registry = availableRegistries.find(registry => packageName.startsWith(registry));
Iif (registry) {
return registry;
}
}
for (const scope of [this.getScope(packageName), '']) {
const registry = this.getScopedOption(scope, 'registry') || this.registries.yarn.getScopedOption(scope, 'registry');
Eif (registry) {
return String(registry);
}
}
return DEFAULT_REGISTRY;
}
getAuth(packageName) {
if (this.token) {
return this.token;
}
for (let registry of [this.getRegistry(packageName), '', DEFAULT_REGISTRY]) {
registry = registry.replace(/^https?:/, '');
// Check for bearer token.
let auth = this.getScopedOption(registry.replace(/\/?$/, '/'), '_authToken');
if (auth) {
return `Bearer ${String(auth)}`;
}
// Check for basic auth token.
auth = this.getScopedOption(registry, '_auth');
if (auth) {
return `Basic ${String(auth)}`;
}
// Check for basic username/password auth.
const username = this.getScopedOption(registry, 'username');
const password = this.getScopedOption(registry, '_password');
if (username && password) {
const pw = new Buffer(String(password), 'base64').toString();
return 'Basic ' + new Buffer(String(username) + ':' + pw).toString('base64');
}
}
return '';
}
getScopedOption(scope, option) {
return this.getOption(scope + (scope ? ':' : '') + option);
}
}
exports.default = NpmRegistry;
NpmRegistry.filename = 'package.json';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 748 748 310 748 310 748 8 748 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DEFAULTS = undefined;
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _constants;
function _load_constants() {
return _constants = require('../constants.js');
}
var _npmRegistry;
function _load_npmRegistry() {
return _npmRegistry = _interopRequireDefault(require('./npm-registry.js'));
}
var _stringify;
function _load_stringify() {
return _stringify = _interopRequireDefault(require('../lockfile/stringify.js'));
}
var _parse;
function _load_parse() {
return _parse = _interopRequireDefault(require('../lockfile/parse.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const userHome = require('../util/user-home-dir').default;
const path = require('path');
const pkg = require('../../package.json');
const DEFAULTS = exports.DEFAULTS = {
'version-tag-prefix': 'v',
'version-git-tag': true,
'version-git-sign': false,
'version-git-message': 'v%s',
'init-version': '1.0.0',
'init-license': 'MIT',
'save-prefix': '^',
'ignore-scripts': false,
'ignore-optional': false,
registry: (_constants || _load_constants()).YARN_REGISTRY,
'strict-ssl': true,
'user-agent': [`yarn/${pkg.version}`, 'npm/?', `node/${process.version}`, process.platform, process.arch].join(' ')
};
const npmMap = {
'version-git-sign': 'sign-git-tag',
'version-tag-prefix': 'tag-version-prefix',
'version-git-tag': 'git-tag-version',
'version-git-message': 'message'
};
class YarnRegistry extends (_npmRegistry || _load_npmRegistry()).default {
constructor(cwd, registries, requestManager) {
super(cwd, registries, requestManager);
this.homeConfigLoc = path.join(userHome, '.yarnrc');
this.homeConfig = {};
}
getOption(key) {
let val = this.config[key];
// if this isn't set in a yarn config, then use npm
if (typeof val === 'undefined') {
val = this.registries.npm.getOption(npmMap[key]);
}
if (typeof val === 'undefined') {
val = this.registries.npm.getOption(key);
}
// if this isn't set in a yarn config or npm config, then use the default (or undefined)
if (typeof val === 'undefined') {
val = DEFAULTS[key];
}
return val;
}
loadConfig() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
for (const _ref of yield _this.getPossibleConfigLocations('.yarnrc')) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 3);
const isHome = _ref2[0];
const loc = _ref2[1];
const file = _ref2[2];
const config = (0, (_parse || _load_parse()).default)(file, loc);
if (isHome) {
_this.homeConfig = config;
}
// normalize offline mirror path relative to the current yarnrc
const offlineLoc = config['yarn-offline-mirror'];
// don't normalize if we already have a mirror path
if (!_this.config['yarn-offline-mirror'] && offlineLoc) {
const mirrorLoc = config['yarn-offline-mirror'] = path.resolve(path.dirname(loc), offlineLoc);
yield (_fs || _load_fs()).mkdirp(mirrorLoc);
}
_this.config = Object.assign({}, config, _this.config);
}
// default yarn config
_this.config = Object.assign({}, DEFAULTS, _this.config);
})();
}
saveHomeConfig(config) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
YarnRegistry.normalizeConfig(config);
for (const key in config) {
const val = config[key];
// if the current config key was taken from home config then update
// the global config
if (_this2.homeConfig[key] === _this2.config[key]) {
_this2.config[key] = val;
}
// update just the home config
_this2.homeConfig[key] = config[key];
}
yield (_fs || _load_fs()).writeFilePreservingEol(_this2.homeConfigLoc, `${(0, (_stringify || _load_stringify()).default)(_this2.homeConfig)}\n`);
})();
}
}
exports.default = YarnRegistry;
YarnRegistry.filename = 'yarn.json';
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| base-reporter.js | 61.62% | (61 / 99) | 50% | (32 / 64) | 37.5% | (18 / 48) | 65.17% | (58 / 89) | |
| format.js | 50% | (3 / 6) | 100% | (0 / 0) | 0% | (0 / 1) | 50% | (3 / 6) | |
| index.js | 69.7% | (23 / 33) | 31.25% | (5 / 16) | 23.08% | (3 / 13) | 68.75% | (22 / 32) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 5656 19377 19377 19377 19377 1 1 1 1 1 1 1 1 1 1 1 1 1 5656 5656 5656 19377 5656 5656 19377 5651 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
exports.stringifyLangArgs = stringifyLangArgs;
var _format;
function _load_format() {
return _format = require('./format.js');
}
var _index;
function _load_index() {
return _index = _interopRequireWildcard(require('./lang/index.js'));
}
var _isCi;
function _load_isCi() {
return _isCi = _interopRequireDefault(require('is-ci'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint no-unused-vars: 0 */
const util = require('util');
const EventEmitter = require('events').EventEmitter;
function stringifyLangArgs(args) {
return args.map(function (val) {
Iif (val != null && val.inspect) {
return val.inspect();
} else {
try {
const str = JSON.stringify(val) || val + '';
// should match all "u001b" that follow an odd number of backslashes and convert them to ESC
// we do this because the JSON.stringify process has escaped these characters
return str.replace(/((?:^|[^\\])(?:\\{2})*)\\u001[bB]/g, '$1\u001b');
} catch (e) {
return util.inspect(val);
}
}
});
}
class BaseReporter {
constructor() {
let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const lang = 'en';
this.language = lang;
this.stdout = opts.stdout || process.stdout;
this.stderr = opts.stderr || process.stderr;
this.stdin = opts.stdin || this._getStandardInput();
this.emoji = !!opts.emoji;
this.noProgress = !!opts.noProgress || (_isCi || _load_isCi()).default;
this.isVerbose = !!opts.verbose;
// $FlowFixMe: this is valid!
this.isTTY = this.stdout.isTTY;
this.peakMemory = 0;
this.startTime = Date.now();
this.format = (_format || _load_format()).defaultFormatter;
}
lang(key) {
const msg = (_index || _load_index())[this.language][key] || (_index || _load_index()).en[key];
Iif (!msg) {
throw new ReferenceError(`Unknown language key ${key}`);
}
// stringify args
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
const stringifiedArgs = stringifyLangArgs(args);
// replace $0 placeholders with args
return msg.replace(/\$(\d+)/g, (str, i) => {
return stringifiedArgs[i];
});
}
verbose(msg) {
Iif (this.isVerbose) {
this._verbose(msg);
}
}
verboseInspect(val) {
if (this.isVerbose) {
this._verboseInspect(val);
}
}
_verbose(msg) {}
_verboseInspect(val) {}
_getStandardInput() {
let standardInput;
try {
standardInput = process.stdin;
} catch (e) {
delete process.stdin;
// $FlowFixMe: this is valid!
process.stdin = new EventEmitter();
standardInput = process.stdin;
}
return standardInput;
}
initPeakMemoryCounter() {
this.checkPeakMemory();
this.peakMemoryInterval = setInterval(() => {
this.checkPeakMemory();
}, 1000);
}
checkPeakMemory() {
var _process$memoryUsage = process.memoryUsage();
const heapTotal = _process$memoryUsage.heapTotal;
Eif (heapTotal > this.peakMemory) {
this.peakMemory = heapTotal;
}
}
close() {
Iif (this.peakMemoryInterval) {
clearInterval(this.peakMemoryInterval);
this.peakMemoryInterval = null;
}
}
getTotalTime() {
return Date.now() - this.startTime;
}
// TODO
list(key, items, hints) {}
// Outputs basic tree structure to console
tree(key, obj) {}
// called whenever we begin a step in the CLI.
step(current, total, message, emoji) {}
// a error message has been triggered. this however does not always meant an abrupt
// program end.
error(message) {}
// an info message has been triggered. this provides things like stats and diagnostics.
info(message) {}
// a warning message has been triggered.
warn(message) {}
// a success message has been triggered.
success(message) {}
// a simple log message
log(message) {}
// a shell command has been executed
command(command) {}
// inspect and pretty-print any value
inspect(value) {}
// the screen shown at the very start of the CLI
header(command, pkg) {}
// the screen shown at the very end of the CLI
footer(showPeakMemory) {}
//
table(head, body) {}
// render an activity spinner and return a function that will trigger an update
activity() {
return {
tick(name) {},
end() {}
};
}
//
activitySet(total, workers) {
return {
spinners: Array(workers).fill({
clear() {},
setPrefix() {},
tick() {},
end() {}
}),
end() {}
};
}
//
question(question) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return Promise.reject(new Error('Not implemented'));
}
//
questionAffirm(question) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const condition = true; // trick eslint
while (condition) {
let answer = yield _this.question(question);
answer = answer.toLowerCase();
if (answer === 'y' || answer === 'yes') {
return true;
}
if (answer === 'n' || answer === 'no') {
return false;
}
_this.error('Invalid answer for question');
}
return false;
})();
}
// prompt the user to select an option from an array
select(header, question, options) {
return Promise.reject(new Error('Not implemented'));
}
// render a progress bar and return a function which when called will trigger an update
progress(total) {
return function () {};
}
// utility function to disable progress bar
disableProgress() {
this.noProgress = true;
}
}
exports.default = BaseReporter;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function formatFunction() {
for (var _len = arguments.length, strs = Array(_len), _key = 0; _key < _len; _key++) {
strs[_key] = arguments[_key];
}
return strs.join(' ');
}
const defaultFormatter = exports.defaultFormatter = {
bold: formatFunction,
dim: formatFunction,
italic: formatFunction,
underline: formatFunction,
inverse: formatFunction,
strikethrough: formatFunction,
black: formatFunction,
red: formatFunction,
green: formatFunction,
yellow: formatFunction,
blue: formatFunction,
magenta: formatFunction,
cyan: formatFunction,
white: formatFunction,
gray: formatFunction,
grey: formatFunction,
stripColor: formatFunction
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _consoleReporter;
function _load_consoleReporter() {
return _consoleReporter = require('./console/console-reporter.js');
}
Object.defineProperty(exports, 'ConsoleReporter', {
enumerable: true,
get: function () {
return _interopRequireDefault(_consoleReporter || _load_consoleReporter()).default;
}
});
var _bufferReporter;
function _load_bufferReporter() {
return _bufferReporter = require('./buffer-reporter.js');
}
Object.defineProperty(exports, 'BufferReporter', {
enumerable: true,
get: function () {
return _interopRequireDefault(_bufferReporter || _load_bufferReporter()).default;
}
});
var _eventReporter;
function _load_eventReporter() {
return _eventReporter = require('./event-reporter.js');
}
Object.defineProperty(exports, 'EventReporter', {
enumerable: true,
get: function () {
return _interopRequireDefault(_eventReporter || _load_eventReporter()).default;
}
});
var _jsonReporter;
function _load_jsonReporter() {
return _jsonReporter = require('./json-reporter.js');
}
Object.defineProperty(exports, 'JSONReporter', {
enumerable: true,
get: function () {
return _interopRequireDefault(_jsonReporter || _load_jsonReporter()).default;
}
});
var _noopReporter;
function _load_noopReporter() {
return _noopReporter = require('./noop-reporter.js');
}
Object.defineProperty(exports, 'NoopReporter', {
enumerable: true,
get: function () {
return _interopRequireDefault(_noopReporter || _load_noopReporter()).default;
}
});
var _baseReporter;
function _load_baseReporter() {
return _baseReporter = require('./base-reporter.js');
}
Object.defineProperty(exports, 'Reporter', {
enumerable: true,
get: function () {
return _interopRequireDefault(_baseReporter || _load_baseReporter()).default;
}
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| console-reporter.js | 31.69% | (58 / 183) | 20.88% | (19 / 91) | 50% | (21 / 42) | 32.02% | (57 / 178) | |
| spinner-progress.js | 96.97% | (32 / 33) | 66.67% | (12 / 18) | 85.71% | (6 / 7) | 96.88% | (31 / 32) | |
| util.js | 62.79% | (27 / 43) | 41.67% | (5 / 12) | 75% | (3 / 4) | 62.79% | (27 / 43) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 5 5 2 2 4 4 4 4 1 1 1 1 1 7 7 9 9 1 1 1 1 1 1 1 1 1 201 1 1 6 6 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _baseReporter;
function _load_baseReporter() {
return _baseReporter = _interopRequireDefault(require('../base-reporter.js'));
}
var _progressBar;
function _load_progressBar() {
return _progressBar = _interopRequireDefault(require('./progress-bar.js'));
}
var _spinnerProgress;
function _load_spinnerProgress() {
return _spinnerProgress = _interopRequireDefault(require('./spinner-progress.js'));
}
var _util;
function _load_util() {
return _util = require('./util.js');
}
var _misc;
function _load_misc() {
return _misc = require('../../util/misc.js');
}
var _treeHelper;
function _load_treeHelper() {
return _treeHelper = require('./helpers/tree-helper.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('util');
const inspect = _require.inspect;
const readline = require('readline');
const chalk = require('chalk');
const read = require('read');
class ConsoleReporter extends (_baseReporter || _load_baseReporter()).default {
constructor(opts) {
super(opts);
this._lastCategorySize = 0;
this.format = chalk;
}
_prependEmoji(msg, emoji) {
Iif (this.emoji && emoji && this.isTTY) {
msg = `${emoji} ${msg}`;
}
return msg;
}
_logCategory(category, color, msg) {
this._lastCategorySize = category.length;
this._log(`${this.format[color](category)} ${msg}`);
}
_verbose(msg) {
this._logCategory('verbose', 'grey', `${process.uptime()} ${msg}`);
}
_verboseInspect(obj) {
this.inspect(obj);
}
table(head, body) {
//
head = head.map(field => this.format.underline(field));
//
const rows = [head].concat(body);
// get column widths
const cols = [];
for (let i = 0; i < head.length; i++) {
const widths = rows.map(row => this.format.stripColor(row[i]).length);
cols[i] = Math.max(...widths);
}
//
const builtRows = rows.map(row => {
for (let i = 0; i < row.length; i++) {
const field = row[i];
const padding = cols[i] - this.format.stripColor(field).length;
row[i] = field + ' '.repeat(padding);
}
return row.join(' ');
});
this.log(builtRows.join('\n'));
}
step(current, total, msg, emoji) {
msg = this._prependEmoji(msg, emoji);
Iif (msg.endsWith('?')) {
msg = `${(0, (_misc || _load_misc()).removeSuffix)(msg, '?')}...?`;
} else {
msg += '...';
}
this.log(`${this.format.dim(`[${current}/${total}]`)} ${msg}`);
}
inspect(value) {
if (typeof value !== 'number' && typeof value !== 'string') {
value = inspect(value, {
breakLength: 0,
colors: true,
depth: null,
maxArrayLength: null
});
}
this.log('' + value);
}
list(key, items, hints) {
const gutterWidth = (this._lastCategorySize || 2) - 1;
if (hints) {
for (const item of items) {
this._log(`${' '.repeat(gutterWidth)}- ${item}`);
this._log(` ${' '.repeat(gutterWidth)} ${hints[item]}`);
}
} else {
for (const item of items) {
this._log(`${' '.repeat(gutterWidth)}- ${item}`);
}
}
}
header(command, pkg) {
this.log(this.format.bold(`${pkg.name} ${command} v${pkg.version}`));
}
footer(showPeakMemory) {
const totalTime = (this.getTotalTime() / 1000).toFixed(2);
let msg = `Done in ${totalTime}s.`;
Iif (showPeakMemory) {
const peakMemory = (this.peakMemory / 1024 / 1024).toFixed(2);
msg += ` Peak memory usage ${peakMemory}MB.`;
}
this.log(this._prependEmoji(msg, '✨'));
}
log(msg) {
this._lastCategorySize = 0;
this._log(msg);
}
_log(msg) {
(0, (_util || _load_util()).clearLine)(this.stdout);
this.stdout.write(`${msg}\n`);
}
success(msg) {
this._logCategory('success', 'green', msg);
}
error(msg) {
(0, (_util || _load_util()).clearLine)(this.stderr);
this.stderr.write(`${this.format.red('error')} ${msg}\n`);
}
info(msg) {
this._logCategory('info', 'blue', msg);
}
command(command) {
this.log(this.format.dim(`$ ${command}`));
}
warn(msg) {
(0, (_util || _load_util()).clearLine)(this.stderr);
this.stderr.write(`${this.format.yellow('warning')} ${msg}\n`);
}
question(question) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!process.stdout.isTTY) {
return Promise.reject(new Error("Can't answer a question unless a user TTY"));
}
return new Promise((resolve, reject) => {
read({
prompt: `${this.format.dim('question')} ${question}: `,
silent: !!options.password,
output: this.stdout,
input: this.stdin
}, (err, answer) => {
if (err) {
if (err.message === 'canceled') {
process.exit(1);
} else {
reject(err);
}
} else {
if (!answer && options.required) {
this.error(this.lang('answerRequired'));
resolve(this.question(question, options));
} else {
resolve(answer);
}
}
});
});
}
// handles basic tree output to console
tree(key, trees) {
//
const output = (_ref, level, end) => {
let name = _ref.name,
children = _ref.children,
hint = _ref.hint,
color = _ref.color;
const formatter = this.format;
const out = (0, (_treeHelper || _load_treeHelper()).getFormattedOutput)({ end, level, hint, color, name, formatter });
this.stdout.write(out);
if (children && children.length) {
(0, (_treeHelper || _load_treeHelper()).recurseTree)((0, (_treeHelper || _load_treeHelper()).sortTrees)(children), level, output);
}
};
(0, (_treeHelper || _load_treeHelper()).recurseTree)((0, (_treeHelper || _load_treeHelper()).sortTrees)(trees), -1, output);
}
activitySet(total, workers) {
Eif (!this.isTTY || this.noProgress) {
return super.activitySet(total, workers);
}
const spinners = [];
for (let i = 1; i < workers; i++) {
this.log('');
}
for (let i = 0; i < workers; i++) {
const spinner = new (_spinnerProgress || _load_spinnerProgress()).default(this.stderr, i);
spinner.start();
let prefix = null;
let current = 0;
const updatePrefix = () => {
spinner.setPrefix(`${this.format.dim(`[${current === 0 ? '-' : current}/${total}]`)} `);
};
const clear = () => {
prefix = null;
current = 0;
updatePrefix();
spinner.setText('waiting...');
};
clear();
spinners.unshift({
clear,
setPrefix(_current, _prefix) {
current = _current;
prefix = _prefix;
spinner.setText(prefix);
updatePrefix();
},
tick(msg) {
if (prefix) {
msg = `${prefix}: ${msg}`;
}
spinner.setText(msg);
},
end() {
spinner.stop();
}
});
}
return {
spinners,
end: () => {
for (const spinner of spinners) {
spinner.end();
}
readline.moveCursor(this.stdout, 0, -workers + 1);
}
};
}
activity() {
Iif (!this.isTTY) {
return {
tick() {},
end() {}
};
}
const spinner = new (_spinnerProgress || _load_spinnerProgress()).default(this.stderr);
spinner.start();
return {
tick(name) {
spinner.setText(name);
},
end() {
spinner.stop();
}
};
}
select(header, question, options) {
if (!this.isTTY) {
return Promise.reject(new Error("Can't answer a question unless a user TTY"));
}
const rl = readline.createInterface({
input: this.stdin,
output: this.stdout,
terminal: true
});
const questions = options.map(opt => opt.name);
const answers = options.map(opt => opt.value);
function toIndex(input) {
const index = answers.indexOf(input);
if (index >= 0) {
return index;
} else {
return +input;
}
}
return new Promise(resolve => {
this.info(header);
for (let i = 0; i < questions.length; i++) {
this.log(` ${this.format.dim(`${i + 1})`)} ${questions[i]}`);
}
const ask = () => {
rl.question(`${question}: `, input => {
let index = toIndex(input);
if (isNaN(index)) {
this.log('Not a number');
ask();
return;
}
if (index <= 0 || index > options.length) {
this.log('Outside answer range');
ask();
return;
}
// get index
index--;
rl.close();
resolve(answers[index]);
});
};
ask();
});
}
progress(count) {
Eif (this.noProgress || count <= 0) {
return function () {
// noop
};
}
if (!this.isTTY) {
return function () {
// TODO what should the behaviour here be? we could buffer progress messages maybe
};
}
const bar = new (_progressBar || _load_progressBar()).default(count, this.stderr);
bar.render();
return function () {
bar.tick();
};
}
}
exports.default = ConsoleReporter;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 201 1 1 28 27 28 28 28 28 28 28 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _util;
function _load_util() {
return _util = require('./util.js');
}
class Spinner {
constructor() {
let stdout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : process.stderr;
let lineNumber = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
this.current = 0;
this.prefix = '';
this.lineNumber = lineNumber;
this.stdout = stdout;
this.delay = 60;
this.chars = Spinner.spinners[28].split('');
this.text = '';
this.id = null;
}
setPrefix(prefix) {
this.prefix = prefix;
}
setText(text) {
this.text = text;
}
start() {
this.current = 0;
this.render();
}
render() {
if (this.id) {
clearTimeout(this.id);
}
// build line ensuring we don't wrap to the next line
let msg = `${this.prefix}${this.chars[this.current]} ${this.text}`;
const columns = typeof this.stdout.columns === 'number' ? this.stdout.columns : 100;
msg = msg.slice(0, columns);
(0, (_util || _load_util()).writeOnNthLine)(this.stdout, this.lineNumber, msg);
this.current = ++this.current % this.chars.length;
this.id = setTimeout(() => this.render(), this.delay);
}
stop() {
Eif (this.id) {
clearTimeout(this.id);
this.id = null;
}
(0, (_util || _load_util()).clearNthLine)(this.stdout, this.lineNumber);
}
}
exports.default = Spinner;
Spinner.spinners = ['|/-\\', '⠂-–—–-', '◐◓◑◒', '◴◷◶◵', '◰◳◲◱', '▖▘▝▗', '■□▪▫', '▌▀▐▄', '▉▊▋▌▍▎▏▎▍▌▋▊▉', '▁▃▄▅▆▇█▇▆▅▄▃', '←↖↑↗→↘↓↙', '┤┘┴└├┌┬┐', '◢◣◤◥', '.oO°Oo.', '.oO@*', '🌍🌎🌏', '◡◡ ⊙⊙ ◠◠', '☱☲☴', '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏', '⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓', '⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆', '⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋', '⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁', '⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈', '⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈', '⢄⢂⢁⡁⡈⡐⡠', '⢹⢺⢼⣸⣇⡧⡗⡏', '⣾⣽⣻⢿⡿⣟⣯⣷', '⠁⠂⠄⡀⢀⠠⠐⠈'];
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | 1 1 1 1 1 1 1 1 1 1 1 10 10 10 1 1 28 28 28 28 28 28 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.clearLine = clearLine;
exports.toStartOfLine = toStartOfLine;
exports.writeOnNthLine = writeOnNthLine;
exports.clearNthLine = clearNthLine;
const readline = require('readline');
var _require = require('chalk');
const supportsColor = _require.supportsColor;
const CLEAR_WHOLE_LINE = 0;
const CLEAR_RIGHT_OF_CURSOR = 1;
function clearLine(stdout) {
Iif (!supportsColor) {
return;
}
readline.clearLine(stdout, CLEAR_WHOLE_LINE);
readline.cursorTo(stdout, 0);
}
function toStartOfLine(stdout) {
if (!supportsColor) {
return;
}
readline.cursorTo(stdout, 0);
}
function writeOnNthLine(stdout, n, msg) {
Iif (!supportsColor) {
return;
}
Eif (n == 0) {
readline.cursorTo(stdout, 0);
stdout.write(msg);
readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);
return;
}
readline.cursorTo(stdout, 0);
readline.moveCursor(stdout, 0, -n);
stdout.write(msg);
readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);
readline.cursorTo(stdout, 0);
readline.moveCursor(stdout, 0, n);
}
function clearNthLine(stdout, n) {
Iif (!supportsColor) {
return;
}
Eif (n == 0) {
clearLine(stdout);
return;
}
readline.cursorTo(stdout, 0);
readline.moveCursor(stdout, 0, -n);
readline.clearLine(stdout, CLEAR_WHOLE_LINE);
readline.moveCursor(stdout, 0, n);
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/* eslint max-len: 0 */
const messages = {
upToDate: 'Already up-to-date.',
folderInSync: 'Folder in sync.',
nothingToInstall: 'Nothing to install.',
resolvingPackages: 'Resolving packages',
fetchingPackages: 'Fetching packages',
linkingDependencies: 'Linking dependencies',
rebuildingPackages: 'Rebuilding all packages',
buildingFreshPackages: 'Building fresh packages',
cleaningModules: 'Cleaning modules',
bumpingVersion: 'Bumping version',
savingHar: 'Saving HAR file: $0',
answer: 'Answer?',
usage: 'Usage',
installCommandRenamed: '`install` has been replaced with `add` to add new dependencies. Run $0 instead.',
waitingInstance: 'Waiting for the other yarn instance to finish',
offlineRetrying: 'There appears to be trouble with your network connection. Retrying...',
clearedCache: 'Cleared cache.',
packWroteTarball: 'Wrote tarball to $0.',
manifestPotentialTypo: 'Potential typo $0, did you mean $1?',
manifestBuiltinModule: '$0 is also the name of a node core module',
manifestNameDot: "Name can't start with a dot",
manifestNameIllegalChars: 'Name contains illegal characters',
manifestNameBlacklisted: 'Name is blacklisted',
manifestLicenseInvalid: 'License should be a valid SPDX license expression',
manifestLicenseNone: 'No license field',
manifestStringExpected: '$0 is not a string',
manifestDependencyCollision: '$0 has dependency $1 with range $2 that collides with a dependency in $3 of the same name with version $4',
manifestDirectoryNotFound: 'Unable to read $0 directory of module $1',
verboseFileCopy: 'Copying $0 to $1.',
verboseFileLink: 'Creating hardlink at $0 to $1.',
verboseFileSymlink: 'Creating symlink at $0 to $1.',
verboseFileSkip: 'Skipping copying of file $0 as the file at $1 is the same size ($2) and mtime ($3).',
verboseFileSkipSymlink: 'Skipping copying of $0 as the file at $1 is the same symlink ($2).',
verboseFileSkipHardlink: 'Skipping copying of $0 as the file at $1 is the same hardlink ($2).',
verboseFileRemoveExtraneous: 'Removing extraneous file $0.',
verboseFilePhantomExtraneous: "File $0 would be marked as extraneous but has been removed as it's listed as a phantom file.",
verboseFileFolder: 'Creating directory $0.',
verboseRequestStart: 'Performing $0 request to $1.',
verboseRequestFinish: 'Request $0 finished with status code $1.',
configSet: 'Set $0 to $1.',
configDelete: 'Deleted $0.',
configNpm: 'npm config',
configYarn: 'yarn config',
couldntFindPackagejson: "Couldn't find a package.json file in $0",
couldntFindMatch: "Couldn't find match for $0 in $1 for $2.",
couldntFindPackageInCache: "Couldn't find any versions for $0 that matches $1 in our cache. Possible versions: $2",
couldntFindVersionThatMatchesRange: "Couldn't find any versions for $0 that matches $1",
chooseVersionFromList: 'Please choose a version from this list:',
moduleNotInManifest: "This module isn't specified in a manifest.",
unknownFolderOrTarball: "Passed folder/tarball doesn't exist,",
unknownPackage: "Couldn't find package $0.",
unknownPackageName: "Couldn't find package name.",
unknownUser: "Couldn't find user $0.",
unknownRegistryResolver: 'Unknown registry resolver $0',
userNotAnOwner: "User $0 isn't an owner of this package.",
invalidVersionArgument: 'Use the $0 flag to create a new version.',
invalidVersion: 'Invalid version supplied.',
requiredVersionInRange: 'Required version in range.',
packageNotFoundRegistry: "Couldn't find package $0 on the $1 registry.",
doesntExist: "$0 doesn't exist.",
missingRequiredPackageKey: `Package $0 doesn't have a $1.`,
invalidAccess: 'Invalid argument for access, expected public or restricted.',
invalidCommand: 'Invalid subcommand. Try $0',
invalidGistFragment: 'Invalid gist fragment $0.',
invalidHostedGitFragment: 'Invalid hosted git fragment $0.',
invalidFragment: 'Invalid fragment $0.',
invalidPackageName: 'Invalid package name.',
couldntFindManifestIn: "Couldn't find manifest in $0.",
shrinkwrapWarning: 'npm-shrinkwrap.json found. This will not be updated or respected. See https://yarnpkg.com/en/docs/migrating-from-npm for more information.',
lockfileOutdated: 'Outdated lockfile. Please run `yarn install` and try again.',
ignoredScripts: 'Ignored scripts due to flag.',
missingAddDependencies: 'Missing list of packages to add to your project.',
yesWarning: 'The yes flag has been set. This will automatically answer yes to all questions which may have security implications.',
networkWarning: "You don't appear to have an internet connection. Try the --offline flag to use the cache for registry queries.",
flatGlobalError: 'The package $0@$1 requires a flat dependency graph. Add `"flat": true` to your package.json and try again.',
noName: `Package doesn't have a name.`,
noVersion: `Package doesn't have a version.`,
answerRequired: 'An answer is required.',
missingWhyDependency: 'Missing package name, folder or path to file to identify why a package has been installed',
bugReport: 'If you think this is a bug, please open a bug report with the information provided in $0.',
unexpectedError: 'An unexpected error occurred: $0.',
jsonError: 'Error parsing JSON at $0, $1.',
noFilePermission: "We don't have permissions to touch the file $0.",
allDependenciesUpToDate: 'All of your dependencies are up to date.',
frozenLockfileError: 'Your lockfile needs to be updated, but yarn was run with `--frozen-lockfile`.',
fileWriteError: 'Could not write file $0: $1',
yarnOutdated: "Your current version of Yarn is out of date. The latest version is $0 while you're on $1.",
yarnOutdatedInstaller: 'To upgrade, download the latest installer at $0.',
yarnOutdatedCommand: 'To upgrade, run the following command:',
tooManyArguments: 'Too many arguments, maximum of $0.',
tooFewArguments: 'Not enough arguments, expected at least $0.',
noArguments: "This command doesn't require any arguments.",
ownerRemoving: 'Removing owner $0 from package $1.',
ownerRemoved: 'Owner removed.',
ownerRemoveError: "Couldn't remove owner.",
ownerGetting: 'Getting owners for package $0',
ownerGettingFailed: "Couldn't get list of owners.",
ownerAlready: 'This user is already an owner of this package.',
ownerAdded: 'Added owner.',
ownerAdding: 'Adding owner $0 to package $1',
ownerAddingFailed: "Couldn't add owner.",
ownerNone: 'No owners.',
teamCreating: 'Creating team',
teamRemoving: 'Removing team',
teamAddingUser: 'Adding user to team',
teamRemovingUser: 'Removing user from team',
teamListing: 'Listing teams',
cleaning: 'Cleaning modules',
cleanCreatingFile: 'Creating $0',
binLinkCollision: "There's already a linked binary called $0 in your global Yarn bin. Could not link this package's $0 bin entry.",
linkCollision: "There's already a module called $0 registered.",
linkMissing: 'No registered module found called $0.',
linkInstallMessage: 'You can now run `yarn link $0` in the projects where you want to use this module and it will be used instead.',
linkRegistered: 'Registered $0.',
linkUnregistered: 'Unregistered $0.',
linkUsing: 'Using linked module for $0.',
commandNotSpecified: 'No command specified.',
binCommands: 'Commands available from binary scripts: ',
possibleCommands: 'Project commands',
commandQuestion: 'Which command would you like to run?',
commandFailed: 'Command failed with exit code $0.',
foundIncompatible: 'Found incompatible module',
incompatibleEngine: 'The engine $0 is incompatible with this module. Expected version $1.',
incompatibleCPU: 'The CPU architecture $0 is incompatible with this module.',
incompatibleOS: 'The platform $0 is incompatible with this module.',
invalidEngine: 'The engine $0 appears to be invalid.',
selfUpdateReleased: 'Replaced current release with $0.',
selfUpdateDownloading: 'Downloading yarn version $0.',
selfUpdateNoNewer: 'Yarn is already using the latest version.',
optionalCompatibilityExcluded: '$0 is an optional dependency and failed compatibility check. Excluding it from installation.',
optionalModuleFail: 'This module is OPTIONAL, you can safely ignore this error',
optionalModuleScriptFail: 'Error running install script for optional dependency: $0',
optionalModuleCleanupFail: 'Could not cleanup build artifacts from failed install: $0',
unmetPeer: '$0 has unmet peer dependency $1.',
incorrectPeer: '$0 has incorrect peer dependency $1.',
savedNewDependency: 'Saved 1 new dependency.',
savedNewDependencies: 'Saved $0 new dependencies.',
foundWarnings: 'Found $0 warnings.',
foundErrors: 'Found $0 errors.',
savedLockfile: 'Saved lockfile.',
noRequiredLockfile: 'No lockfile in this directory. Run `yarn install` to generate one.',
noLockfileFound: 'No lockfile found.',
invalidSemver: 'Invalid semver version',
newVersion: 'New version',
currentVersion: 'Current version',
manualVersionResolution: 'Unable to find a suitable version for $0, please choose one by typing one of the numbers below:',
manualVersionResolutionOption: '$0 which resolved to $1',
createdTag: 'Created tag.',
createdTagFail: "Couldn't add tag.",
deletedTag: 'Deleted tag.',
deletedTagFail: "Couldn't delete tag.",
gettingTags: 'Getting tags',
deletingTags: 'Deleting tag',
creatingTag: 'Creating tag $0 = $1',
whyStart: 'Why do we have the module $0?',
whyFinding: 'Finding dependency',
whyCalculating: 'Calculating file sizes',
whyUnknownMatch: "We couldn't find a match!",
whyInitGraph: 'Initialising dependency graph',
whyWhoKnows: "We don't know why this module exists",
whyDiskSizeWithout: 'Disk size without dependencies: $0',
whyDiskSizeUnique: 'Disk size with unique dependencies: $0',
whyDiskSizeTransitive: 'Disk size with transitive dependencies: $0',
whySharedDependencies: 'Amount of shared dependencies: $0',
whyHoistedTo: `Has been hoisted to $0`,
whyHoistedFromSimple: `This module exists because it's hoisted from $0.`,
whyDependedOnSimple: `This module exists because $0 depends on it.`,
whySpecifiedSimple: `This module exists because it's specified in $0.`,
whyReasons: 'Reasons this module exists',
whyHoistedFrom: 'Hoisted from $0',
whyDependedOn: '$0 depends on it',
whySpecified: `Specified in $0`,
uninstalledPackages: 'Uninstalled packages.',
uninstallRegenerate: 'Regenerating lockfile and installing missing dependencies',
cleanRemovedFiles: 'Removed $0 files',
cleanSavedSize: 'Saved $0 MB.',
npmUsername: 'npm username',
npmPassword: 'npm password',
npmEmail: 'npm email',
loggingIn: 'Logging in',
loggedIn: 'Logged in.',
notRevokingEnvToken: 'Not revoking login token, specified via environment variable.',
notRevokingConfigToken: 'Not revoking login token, specified via config file.',
noTokenToRevoke: 'No login token to revoke.',
revokingToken: 'Revoking token',
revokedToken: 'Revoked login token.',
loginAsPublic: 'Logging in as public',
incorrectCredentials: 'Incorrect username or password.',
clearedCredentials: 'Cleared login credentials.',
publishSame: 'New version is the same as the current version.',
publishFail: "Couldn't publish package.",
publishPrivate: 'Package marked as private, not publishing.',
published: 'Published.',
publishing: 'Publishing',
infoFail: 'Received invalid response from npm.',
malformedRegistryResponse: 'Received malformed response from registry for $0. The registry may be down.',
cantRequestOffline: 'Can\'t make a request in offline mode',
requestManagerNotSetupHAR: 'RequestManager was not setup to capture HAR files',
requestError: 'Request $0 returned a $1',
requestFailed: 'Request failed $0',
tarballNotInNetworkOrCache: '$0: Tarball is not in network and can not be located in cache ($1)',
fetchBadHash: 'Bad hash. Expected $0 but got $1 ',
fetchErrorCorrupt: '$0. Mirror tarball appears to be corrupt. You can resolve this by running:\n\n rm -rf $1\n yarn install',
errorDecompressingTarball: '$0. Error decompressing $1, it appears to be corrupt.',
updateInstalling: 'Installing $0...',
hostedGitResolveError: 'Error connecting to repository. Please, check the url.',
unknownFetcherFor: 'Unknown fetcher for $0',
refusingDownloadGitWithoutCommit: 'Refusing to download the git repo $0 over plain git without a commit hash',
refusingDownloadHTTPWithoutCommit: 'Refusing to download the git repo $0 over HTTP without a commit hash',
refusingDownloadHTTPSWithoutCommit: 'Refusing to download the git repo $0 over HTTPS without a commit hash - possible certificate error?',
packageInstalledWithBinaries: 'Installed $0 with binaries:',
packageHasBinaries: '$0 has binaries:',
packageHasNoBinaries: '$0 has no binaries',
couldBeDeduped: '$0 could be deduped from $1 to $2',
lockfileNotContainPatter: 'Lockfile does not contain pattern: $0',
integrityHashesDontMatch: 'Integrity hashes don\'t match, expected $0 but got $1',
noIntegirtyHashFile: 'Couldn\'t find an integrity hash file',
packageNotInstalled: '$0 not installed',
optionalDepNotInstalled: 'Optional dependency $0 not installed',
packageWrongVersion: '$0 is wrong version: expected $1, got $2',
packageDontSatisfy: '$0 doesn\'t satisfy found match of $1',
lockfileExists: 'Lockfile already exists, not importing.',
skippingImport: 'Skipping import of $0 for $1',
importFailed: 'Import of $0 for $1 failed, resolving normally.',
importResolveFailed: 'Import of $0 failed starting in $1',
importResolvedRangeMatch: 'Using version $0 of $1 instead of $2 for $3'
};
exports.default = messages;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.en = undefined;
var _en;
function _load_en() {
return _en = _interopRequireDefault(require('./en.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.en = (_en || _load_en()).default;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| base-resolver.js | 60% | (9 / 15) | 100% | (0 / 0) | 33.33% | (1 / 3) | 60% | (9 / 15) | |
| index.js | 100% | (51 / 51) | 88.24% | (30 / 34) | 100% | (13 / 13) | 100% | (50 / 50) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 1 201 201 201 201 201 201 201 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
class BaseResolver {
constructor(request, fragment) {
this.resolver = request.resolver;
this.reporter = request.reporter;
this.fragment = fragment;
this.registry = request.registry;
this.request = request;
this.pattern = request.pattern;
this.config = request.config;
}
fork(Resolver, resolveArg) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
const resolver = new Resolver(this.request, ...args);
resolver.registry = this.registry;
return resolver.resolve(resolveArg);
}
resolve() {
throw new Error('Not implemented');
}
}
exports.default = BaseResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 175 429 429 48 127 1 2 2 2 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hostedGit = exports.exotics = exports.registries = undefined;
exports.hostedGitFragmentToGitUrl = hostedGitFragmentToGitUrl;
var _npmResolver;
function _load_npmResolver() {
return _npmResolver = _interopRequireDefault(require('./registries/npm-resolver.js'));
}
var _yarnResolver;
function _load_yarnResolver() {
return _yarnResolver = _interopRequireDefault(require('./registries/yarn-resolver.js'));
}
var _gitResolver;
function _load_gitResolver() {
return _gitResolver = _interopRequireDefault(require('./exotics/git-resolver.js'));
}
var _tarballResolver;
function _load_tarballResolver() {
return _tarballResolver = _interopRequireDefault(require('./exotics/tarball-resolver.js'));
}
var _githubResolver;
function _load_githubResolver() {
return _githubResolver = _interopRequireDefault(require('./exotics/github-resolver.js'));
}
var _fileResolver;
function _load_fileResolver() {
return _fileResolver = _interopRequireDefault(require('./exotics/file-resolver.js'));
}
var _gitlabResolver;
function _load_gitlabResolver() {
return _gitlabResolver = _interopRequireDefault(require('./exotics/gitlab-resolver.js'));
}
var _gistResolver;
function _load_gistResolver() {
return _gistResolver = _interopRequireDefault(require('./exotics/gist-resolver.js'));
}
var _bitbucketResolver;
function _load_bitbucketResolver() {
return _bitbucketResolver = _interopRequireDefault(require('./exotics/bitbucket-resolver.js'));
}
var _hostedGitResolver;
function _load_hostedGitResolver() {
return _hostedGitResolver = require('./exotics/hosted-git-resolver.js');
}
var _registryResolver;
function _load_registryResolver() {
return _registryResolver = _interopRequireDefault(require('./exotics/registry-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const registries = exports.registries = {
npm: (_npmResolver || _load_npmResolver()).default,
yarn: (_yarnResolver || _load_yarnResolver()).default
};
//
const exotics = exports.exotics = {
git: (_gitResolver || _load_gitResolver()).default,
tarball: (_tarballResolver || _load_tarballResolver()).default,
github: (_githubResolver || _load_githubResolver()).default,
file: (_fileResolver || _load_fileResolver()).default,
gitlab: (_gitlabResolver || _load_gitlabResolver()).default,
gist: (_gistResolver || _load_gistResolver()).default,
bitbucket: (_bitbucketResolver || _load_bitbucketResolver()).default
};
//
const hostedGit = exports.hostedGit = {
github: (_githubResolver || _load_githubResolver()).default,
gitlab: (_gitlabResolver || _load_gitlabResolver()).default,
bitbucket: (_bitbucketResolver || _load_bitbucketResolver()).default
};
function hostedGitFragmentToGitUrl(fragment, reporter) {
for (const key in hostedGit) {
const Resolver = hostedGit[key];
if (Resolver.isVersion(fragment)) {
return Resolver.getGitHTTPUrl((0, (_hostedGitResolver || _load_hostedGitResolver()).explodeHostedGitFragment)(fragment, reporter));
}
}
return fragment;
}
//
for (const key in registries) {
var _class, _temp;
const RegistryResolver = registries[key];
exotics[key] = (_temp = _class = class extends (_registryResolver || _load_registryResolver()).default {}, _class.protocol = key, _class.factory = RegistryResolver, _temp);
}
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| bitbucket-resolver.js | 69.23% | (9 / 13) | 62.5% | (5 / 8) | 33.33% | (2 / 6) | 66.67% | (8 / 12) | |
| exotic-resolver.js | 90.91% | (10 / 11) | 75% | (6 / 8) | 100% | (3 / 3) | 90% | (9 / 10) | |
| file-resolver.js | 29.58% | (21 / 71) | 10.2% | (5 / 49) | 16.67% | (2 / 12) | 32.79% | (20 / 61) | |
| gist-resolver.js | 42.5% | (17 / 40) | 20.83% | (5 / 24) | 22.22% | (2 / 9) | 53.33% | (16 / 30) | |
| git-resolver.js | 28.18% | (31 / 110) | 8.11% | (6 / 74) | 15.79% | (3 / 19) | 30.3% | (30 / 99) | |
| github-resolver.js | 94.44% | (17 / 18) | 75% | (9 / 12) | 100% | (7 / 7) | 94.12% | (16 / 17) | |
| gitlab-resolver.js | 69.23% | (9 / 13) | 62.5% | (5 / 8) | 33.33% | (2 / 6) | 66.67% | (8 / 12) | |
| hosted-git-resolver.js | 70.16% | (87 / 124) | 40.54% | (30 / 74) | 76% | (19 / 25) | 69.92% | (86 / 123) | |
| registry-resolver.js | 50% | (9 / 18) | 41.67% | (5 / 12) | 40% | (2 / 5) | 47.06% | (8 / 17) | |
| tarball-resolver.js | 38.16% | (29 / 76) | 36.36% | (16 / 44) | 28.57% | (4 / 14) | 42.42% | (28 / 66) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _hostedGitResolver;
function _load_hostedGitResolver() {
return _hostedGitResolver = _interopRequireDefault(require('./hosted-git-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class BitbucketResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default {
static getTarballUrl(parts, hash) {
return `https://${this.hostname}/${parts.user}/${parts.repo}/get/${hash}.tar.gz`;
}
static getGitHTTPUrl(parts) {
return `https://${this.hostname}/${parts.user}/${parts.repo}.git`;
}
static getGitSSHUrl(parts) {
return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`;
}
static getHTTPFileUrl(parts, filename, commit) {
return `https://${this.hostname}/${parts.user}/${parts.repo}/raw/${commit}/${filename}`;
}
}
exports.default = BitbucketResolver;
BitbucketResolver.hostname = 'bitbucket.org';
BitbucketResolver.protocol = 'bitbucket';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 1 1 1 1 1 3848 3848 3848 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _baseResolver;
function _load_baseResolver() {
return _baseResolver = _interopRequireDefault(require('../base-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class ExoticResolver extends (_baseResolver || _load_baseResolver()).default {
static isVersion(pattern) {
const proto = this.protocol;
Eif (proto) {
return pattern.startsWith(`${proto}:`);
} else {
throw new Error('No protocol specified');
}
}
}
exports.default = ExoticResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
var _misc;
function _load_misc() {
return _misc = _interopRequireWildcard(require('../../util/misc.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const path = require('path');
class FileResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
this.loc = (_misc || _load_misc()).removePrefix(fragment, 'file:');
}
resolve() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
let loc = _this.loc;
if (!path.isAbsolute(loc)) {
loc = path.join(_this.config.cwd, loc);
}
if (!(yield (_fs || _load_fs()).exists(loc))) {
throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('doesntExist', loc));
}
const manifest = yield _this.config.readManifest(loc, _this.registry);
const registry = manifest._registry;
invariant(registry, 'expected registry');
manifest._remote = {
type: 'copy',
registry,
hash: null,
reference: loc
};
manifest._uid = manifest.version;
// Normalize relative paths; if anything changes, make a copy of the manifest
const dependencies = _this.normalizeDependencyPaths(manifest.dependencies, loc);
const optionalDependencies = _this.normalizeDependencyPaths(manifest.optionalDependencies, loc);
if (dependencies !== manifest.dependencies || optionalDependencies !== manifest.optionalDependencies) {
const _manifest = Object.assign({}, manifest);
if (dependencies != null) {
_manifest.dependencies = dependencies;
}
if (optionalDependencies != null) {
_manifest.optionalDependencies = optionalDependencies;
}
return _manifest;
} else {
return manifest;
}
})();
}
normalizeDependencyPaths(section, loc) {
if (section == null) {
return section;
}
let temp = section;
for (const _ref of (_misc || _load_misc()).entries(section)) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const k = _ref2[0];
const v = _ref2[1];
if (typeof v === 'string' && v.startsWith('file:') && !path.isAbsolute(v)) {
if (temp === section) {
temp = Object.assign({}, section);
}
temp[k] = `file:${path.relative(this.config.cwd, path.join(loc, (_misc || _load_misc()).removePrefix(v, 'file:')))}`;
}
}
return temp;
}
}
exports.default = FileResolver;
FileResolver.protocol = 'file';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.explodeGistFragment = explodeGistFragment;
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _gitResolver;
function _load_gitResolver() {
return _gitResolver = _interopRequireDefault(require('./git-resolver.js'));
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
var _misc;
function _load_misc() {
return _misc = _interopRequireWildcard(require('../../util/misc.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function explodeGistFragment(fragment, reporter) {
fragment = (_misc || _load_misc()).removePrefix(fragment, 'gist:');
const parts = fragment.split('#');
if (parts.length <= 2) {
return {
id: parts[0],
hash: parts[1] || ''
};
} else {
throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidGistFragment', fragment));
}
}
class GistResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
var _explodeGistFragment = explodeGistFragment(fragment, this.reporter);
const id = _explodeGistFragment.id,
hash = _explodeGistFragment.hash;
this.id = id;
this.hash = hash;
}
resolve() {
return this.fork((_gitResolver || _load_gitResolver()).default, false, `https://gist.github.com/${this.id}.git#${this.hash}`);
}
}
exports.default = GistResolver;
GistResolver.protocol = 'gist';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1206 1206 1206 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _index;
function _load_index() {
return _index = require('../index.js');
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _misc;
function _load_misc() {
return _misc = _interopRequireWildcard(require('../../util/misc.js'));
}
var _version;
function _load_version() {
return _version = _interopRequireWildcard(require('../../util/version.js'));
}
var _index2;
function _load_index2() {
return _index2 = require('../../registries/index.js');
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
var _git;
function _load_git() {
return _git = _interopRequireDefault(require('../../util/git.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const urlParse = require('url').parse;
const urlFormat = require('url').format;
// we purposefully omit https and http as those are only valid if they end in the .git extension
const GIT_PROTOCOLS = ['git:', 'git+ssh:', 'git+https:', 'ssh:'];
const GIT_HOSTS = ['github.com', 'gitlab.com', 'bitbucket.com', 'bitbucket.org'];
class GitResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
var _versionUtil$explodeH = (_version || _load_version()).explodeHashedUrl(fragment);
const url = _versionUtil$explodeH.url,
hash = _versionUtil$explodeH.hash;
this.url = url;
this.hash = hash;
}
static isVersion(pattern) {
const parts = urlParse(pattern);
// this pattern hasn't been exploded yet, we'll hit this code path again later once
// we've been normalized #59
Eif (!parts.protocol) {
return false;
}
const pathname = parts.pathname;
if (pathname && pathname.endsWith('.git')) {
// ends in .git
return true;
}
if (GIT_PROTOCOLS.indexOf(parts.protocol) >= 0) {
return true;
}
if (parts.hostname && parts.path) {
const path = parts.path;
if (GIT_HOSTS.indexOf(parts.hostname) >= 0) {
// only if dependency is pointing to a git repo,
// e.g. facebook/flow and not file in a git repo facebook/flow/archive/v1.0.0.tar.gz
return path.split('/').filter(p => !!p).length === 2;
}
}
return false;
}
// This transformUrl util is here to replace colon separators in the pathname
// from private urls. It takes the url parts retrieved using urlFormat and
// returns the associated url. Related to #573, introduced in #2519.
static transformUrl(parts) {
const pathname = parts.pathname ? parts.pathname.replace(/^\/:/, '/') : '';
return urlFormat((0, (_extends2 || _load_extends()).default)({}, parts, { pathname }));
}
resolve(forked) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
let tryRegistry = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (registry) {
const filename = (_index2 || _load_index2()).registries[registry].filename;
const file = yield client.getFile(filename);
if (!file) {
return null;
}
const json = yield config.readJson(`${transformedUrl}/${filename}`, function () {
return JSON.parse(file);
});
json._uid = commit;
json._remote = {
resolved: `${transformedUrl}#${commit}`,
type: 'git',
reference: transformedUrl,
hash: commit,
registry
};
return json;
});
return function tryRegistry(_x) {
return _ref.apply(this, arguments);
};
})();
const url = _this.url;
// shortcut for hosted git. we will fallback to a GitResolver if the hosted git
// optimisations fail which the `forked` flag indicates so we don't get into an
// infinite loop
const parts = urlParse(url);
if (false && !forked && !parts.auth && parts.pathname) {
// check if this git url uses any of the hostnames defined in our hosted git resolvers
for (const name in (_index || _load_index()).hostedGit) {
const Resolver = (_index || _load_index()).hostedGit[name];
if (Resolver.hostname !== parts.hostname) {
continue;
}
// we have a match! clean up the pathname of url artifacts
let pathname = parts.pathname;
pathname = (_misc || _load_misc()).removePrefix(pathname, '/'); // remove prefixed slash
pathname = (_misc || _load_misc()).removeSuffix(pathname, '.git'); // remove .git suffix if present
const url = `${pathname}${_this.hash ? '#' + decodeURIComponent(_this.hash) : ''}`;
return _this.fork(Resolver, false, url);
}
}
// get from lockfile
const shrunk = _this.request.getLocked('git');
if (shrunk) {
return shrunk;
}
const config = _this.config;
const transformedUrl = GitResolver.transformUrl(parts);
const client = new (_git || _load_git()).default(config, transformedUrl, _this.hash);
const commit = yield client.init();
const file = yield tryRegistry(_this.registry);
if (file) {
return file;
}
for (const registry in (_index2 || _load_index2()).registries) {
if (registry === _this.registry) {
continue;
}
const file = yield tryRegistry(registry);
if (file) {
return file;
}
}
throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('couldntFindManifestIn', transformedUrl));
})();
}
}
exports.default = GitResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 1 1 1 1 1 778 778 52 726 2 2 50 2 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _hostedGitResolver;
function _load_hostedGitResolver() {
return _hostedGitResolver = _interopRequireDefault(require('./hosted-git-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class GitHubResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default {
static isVersion(pattern) {
// github proto
Iif (pattern.startsWith('github:')) {
return true;
}
// github shorthand
if (/^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(pattern)) {
return true;
}
return false;
}
static getTarballUrl(parts, hash) {
return `https://codeload.${this.hostname}/${parts.user}/${parts.repo}/tar.gz/${hash}`;
}
static getGitSSHUrl(parts) {
return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`;
}
static getGitHTTPUrl(parts) {
return `https://${this.hostname}/${parts.user}/${parts.repo}.git`;
}
static getHTTPFileUrl(parts, filename, commit) {
return `https://raw.githubusercontent.com/${parts.user}/${parts.repo}/${commit}/${filename}`;
}
}
exports.default = GitHubResolver;
GitHubResolver.protocol = 'github';
GitHubResolver.hostname = 'github.com';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _hostedGitResolver;
function _load_hostedGitResolver() {
return _hostedGitResolver = _interopRequireDefault(require('./hosted-git-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class GitLabResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default {
static getTarballUrl(parts, hash) {
return `https://${this.hostname}/${parts.user}/${parts.repo}/repository/archive.tar.gz?ref=${hash}`;
}
static getGitHTTPUrl(parts) {
return `https://${this.hostname}/${parts.user}/${parts.repo}.git`;
}
static getGitSSHUrl(parts) {
return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`;
}
static getHTTPFileUrl(parts, filename, commit) {
return `https://${this.hostname}/${parts.user}/${parts.repo}/raw/${commit}/${filename}`;
}
}
exports.default = GitLabResolver;
GitLabResolver.hostname = 'gitlab.com';
GitLabResolver.protocol = 'gitlab';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 50 50 50 50 50 50 50 50 50 50 50 50 50 50 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 80 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
exports.explodeHostedGitFragment = explodeHostedGitFragment;
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _index;
function _load_index() {
return _index = require('../../registries/index.js');
}
var _gitResolver;
function _load_gitResolver() {
return _gitResolver = _interopRequireDefault(require('./git-resolver.js'));
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
var _git;
function _load_git() {
return _git = _interopRequireDefault(require('../../util/git.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function explodeHostedGitFragment(fragment, reporter) {
const preParts = fragment.split('@');
Iif (preParts.length > 2) {
fragment = preParts[1] + '@' + preParts[2];
}
const parts = fragment.split(':');
Iif (parts.length == 3) {
// protocol + host + folder
parts[1] = parts[1].indexOf('//') >= 0 ? parts[1].substr(2) : parts[1];
fragment = parts[1] + '/' + parts[2];
} else Iif (parts.length == 2) {
if (parts[0].indexOf('@') == -1) {
// protocol + host
fragment = parts[1];
} else {
// host + folder
fragment = parts[0] + '/' + parts[1];
}
} else Eif (parts.length == 1) {
fragment = parts[0];
} else {
throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidHostedGitFragment', fragment));
}
const userParts = fragment.split('/');
Eif (userParts.length >= 2) {
Iif (userParts[0].indexOf('@') >= 0) {
userParts.shift();
}
const user = userParts.shift();
const repoParts = userParts.join('/').split(/(?:[.]git)?#(.*)/);
Eif (repoParts.length <= 3) {
return {
user,
repo: repoParts[0].replace('.git', ''),
hash: repoParts[1] || ''
};
}
}
throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidHostedGitFragment', fragment));
}
class HostedGitResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
const exploded = this.exploded = explodeHostedGitFragment(fragment, this.reporter);
const user = exploded.user,
repo = exploded.repo,
hash = exploded.hash;
this.user = user;
this.repo = repo;
this.hash = hash;
}
static getTarballUrl(exploded, commit) {
exploded;
commit;
throw new Error('Not implemented');
}
static getGitHTTPUrl(exploded) {
exploded;
throw new Error('Not implemented');
}
static getGitSSHUrl(exploded) {
exploded;
throw new Error('Not implemented');
}
static getHTTPFileUrl(exploded, filename, commit) {
exploded;
filename;
commit;
throw new Error('Not implemented');
}
getRefOverHTTP(url) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const client = new (_git || _load_git()).default(_this.config, url, _this.hash);
let out = yield _this.config.requestManager.request({
url: `${url}/info/refs?service=git-upload-pack`,
queue: _this.resolver.fetchingQueue
});
Eif (out) {
// clean up output
let lines = out.trim().split('\n');
// remove first two lines which contains compatibility info etc
lines = lines.slice(2);
// remove last line which contains the terminator "0000"
lines.pop();
// remove line lengths from start of each line
lines = lines.map(function (line) {
return line.slice(4);
});
out = lines.join('\n');
} else {
throw new Error(_this.reporter.lang('hostedGitResolveError'));
}
const refs = (_git || _load_git()).default.parseRefs(out);
return yield client.setRef(refs);
})();
}
resolveOverHTTP(url) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const shrunk = _this2.request.getLocked('tarball');
Iif (shrunk) {
return shrunk;
}
const commit = yield _this2.getRefOverHTTP(url);
const config = _this2.config;
const tryRegistry = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (registry) {
const filename = (_index || _load_index()).registries[registry].filename;
const href = _this2.constructor.getHTTPFileUrl(_this2.exploded, filename, commit);
const file = yield config.requestManager.request({
url: href,
queue: _this2.resolver.fetchingQueue
});
Iif (!file) {
return null;
}
const tarballUrl = _this2.constructor.getTarballUrl(_this2.exploded, commit);
const json = yield config.readJson(href, function () {
return JSON.parse(file);
});
json._uid = commit;
json._remote = {
resolved: tarballUrl,
type: 'tarball',
reference: tarballUrl,
registry
};
return json;
});
return function tryRegistry(_x) {
return _ref.apply(this, arguments);
};
})();
const file = yield tryRegistry(_this2.registry);
Eif (file) {
return file;
}
for (const registry in (_index || _load_index()).registries) {
if (registry === _this2.registry) {
continue;
}
const file = yield tryRegistry(registry);
if (file) {
return file;
}
}
throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('couldntFindManifestIn', url));
})();
}
hasHTTPCapability(url) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
return (yield _this3.config.requestManager.request({
url,
method: 'HEAD',
queue: _this3.resolver.fetchingQueue,
followRedirect: false
})) !== false;
})();
}
resolve() {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const httpUrl = _this4.constructor.getGitHTTPUrl(_this4.exploded);
const sshUrl = _this4.constructor.getGitSSHUrl(_this4.exploded);
// If we can access the files over HTTP then we should as it's MUCH faster than git
// archive and tarball unarchiving. The HTTP API is only available for public repos
// though.
Eif (yield _this4.hasHTTPCapability(httpUrl)) {
return yield _this4.resolveOverHTTP(httpUrl);
}
// If the url is accessible over git archive then we should immediately delegate to
// the git resolver.
//
// NOTE: Here we use a different url than when we delegate to the git resolver later on.
// This is because `git archive` requires access over ssh and github only allows that
// if you have write permissions
if (yield (_git || _load_git()).default.hasArchiveCapability(sshUrl)) {
const archiveClient = new (_git || _load_git()).default(_this4.config, sshUrl, _this4.hash);
const commit = yield archiveClient.init();
return yield _this4.fork((_gitResolver || _load_gitResolver()).default, true, `${sshUrl}#${commit}`);
}
// fallback to the plain git resolver
return yield _this4.fork((_gitResolver || _load_gitResolver()).default, true, sshUrl);
})();
}
}
exports.default = HostedGitResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 1 1 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class RegistryResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
const match = fragment.match(/^(\S+):(.*?)(@(.*?)|)$/);
if (match) {
this.range = match[4] || 'latest';
this.name = match[2];
} else {
throw new (_errors || _load_errors()).MessageError(this.reporter.lang('invalidFragment', fragment));
}
// $FlowFixMe
this.registry = this.constructor.protocol;
}
resolve() {
return this.fork(this.constructor.factory, false, this.name, this.range);
}
}
exports.default = RegistryResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 603 603 603 402 603 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _tarballFetcher;
function _load_tarballFetcher() {
return _tarballFetcher = _interopRequireDefault(require('../../fetchers/tarball-fetcher.js'));
}
var _exoticResolver;
function _load_exoticResolver() {
return _exoticResolver = _interopRequireDefault(require('./exotic-resolver.js'));
}
var _gitResolver;
function _load_gitResolver() {
return _gitResolver = _interopRequireDefault(require('./git-resolver.js'));
}
var _misc;
function _load_misc() {
return _misc = require('../../util/misc.js');
}
var _version;
function _load_version() {
return _version = _interopRequireWildcard(require('../../util/version.js'));
}
var _crypto;
function _load_crypto() {
return _crypto = _interopRequireWildcard(require('../../util/crypto.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
class TarballResolver extends (_exoticResolver || _load_exoticResolver()).default {
constructor(request, fragment) {
super(request, fragment);
var _versionUtil$explodeH = (_version || _load_version()).explodeHashedUrl(fragment);
const hash = _versionUtil$explodeH.hash,
url = _versionUtil$explodeH.url;
this.hash = hash;
this.url = url;
}
static isVersion(pattern) {
// we can sometimes match git urls which we don't want
Iif ((_gitResolver || _load_gitResolver()).default.isVersion(pattern)) {
return false;
}
// full http url
Iif (pattern.startsWith('http://') || pattern.startsWith('https://')) {
return true;
}
// local file reference - ignore patterns with names
if (pattern.indexOf('@') < 0) {
Iif (pattern.endsWith('.tgz') || pattern.endsWith('.tar.gz')) {
return true;
}
}
return false;
}
resolve() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const shrunk = _this.request.getLocked('tarball');
if (shrunk) {
return shrunk;
}
const url = (0, (_misc || _load_misc()).removePrefix)(_this.url, 'file:');
let hash = _this.hash,
registry = _this.registry;
let pkgJson;
// generate temp directory
const dest = _this.config.getTemp((_crypto || _load_crypto()).hash(url));
if (yield _this.config.isValidModuleDest(dest)) {
var _ref = yield _this.config.readPackageMetadata(dest);
// load from local cache
pkgJson = _ref.package;
hash = _ref.hash;
registry = _ref.registry;
} else {
// delete if invalid
yield (_fs || _load_fs()).unlink(dest);
const fetcher = new (_tarballFetcher || _load_tarballFetcher()).default(dest, {
type: 'tarball',
reference: url,
registry,
hash
}, _this.config, false);
// fetch file and get it's hash
const fetched = yield fetcher.fetch();
pkgJson = fetched.package;
hash = fetched.hash;
registry = pkgJson._registry;
invariant(registry, 'expected registry');
}
// use the commit/tarball hash as the uid as we can't rely on the version as it's not
// in the registry
pkgJson._uid = hash;
// set remote so it can be "fetched"
pkgJson._remote = {
type: 'copy',
resolved: `${url}#${hash}`,
hash,
registry,
reference: dest
};
return pkgJson;
})();
}
}
exports.default = TarballResolver;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| npm-resolver.js | 43.65% | (55 / 126) | 26% | (26 / 100) | 63.16% | (12 / 19) | 46.55% | (54 / 116) | |
| registry-resolver.js | 100% | (11 / 11) | 83.33% | (5 / 6) | 100% | (3 / 3) | 100% | (10 / 10) | |
| yarn-resolver.js | 100% | (7 / 7) | 83.33% | (5 / 6) | 100% | (2 / 2) | 100% | (6 / 6) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 199 199 199 199 199 199 199 199 199 199 199 199 398 398 199 199 199 199 199 199 199 199 199 199 199 199 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _registryResolver;
function _load_registryResolver() {
return _registryResolver = _interopRequireDefault(require('./registry-resolver.js'));
}
var _npmRegistry;
function _load_npmRegistry() {
return _npmRegistry = _interopRequireDefault(require('../../registries/npm-registry.js'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('../../util/map.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
var _constants;
function _load_constants() {
return _constants = require('../../constants.js');
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const inquirer = require('inquirer');
const tty = require('tty');
const invariant = require('invariant');
const path = require('path');
const NPM_REGISTRY = /http[s]:\/\/registry.npmjs.org/g;
class NpmResolver extends (_registryResolver || _load_registryResolver()).default {
static findVersionInRegistryResponse(config, range, body, request) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
Iif (!body['dist-tags']) {
throw new (_errors || _load_errors()).MessageError(config.reporter.lang('malformedRegistryResponse', body.name));
}
Iif (range in body['dist-tags']) {
range = body['dist-tags'][range];
}
const satisfied = yield config.resolveConstraints(Object.keys(body.versions), range);
Eif (satisfied) {
return body.versions[satisfied];
} else if (request && !config.nonInteractive) {
if (request.resolver && request.resolver.activity) {
request.resolver.activity.end();
}
config.reporter.log(config.reporter.lang('couldntFindVersionThatMatchesRange', body.name, range));
let pageSize;
if (process.stdout instanceof tty.WriteStream) {
pageSize = process.stdout.rows - 2;
}
const response = yield inquirer.prompt([{
name: 'package',
type: 'list',
message: config.reporter.lang('chooseVersionFromList'),
choices: Object.keys(body.versions).reverse(),
pageSize
}]);
if (response && response.package) {
return body.versions[response.package];
}
}
throw new (_errors || _load_errors()).MessageError(config.reporter.lang('couldntFindVersionThatMatchesRange', body.name, range));
})();
}
resolveRequest() {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
Iif (_this.config.offline) {
const res = _this.resolveRequestOffline();
if (res != null) {
return res;
}
}
const body = yield _this.config.registries.npm.request((_npmRegistry || _load_npmRegistry()).default.escapeName(_this.name));
Eif (body) {
return yield NpmResolver.findVersionInRegistryResponse(_this.config, _this.range, body, _this.request);
} else {
return null;
}
})();
}
resolveRequestOffline() {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const scope = _this2.config.registries.npm.getScope(_this2.name);
// find modules of this name
const prefix = scope ? _this2.name.split(/\/|%2f/)[1] : `npm-${_this2.name}-`;
invariant(_this2.config.cacheFolder, 'expected packages root');
const cacheFolder = path.join(_this2.config.cacheFolder, scope ? 'npm-' + scope : '');
const files = yield _this2.config.getCache('cachedPackages', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const files = yield (_fs || _load_fs()).readdir(cacheFolder);
const validFiles = [];
for (const name of files) {
// no hidden files
if (name[0] === '.') {
continue;
}
// ensure valid module cache
const dir = path.join(cacheFolder, name);
if (yield _this2.config.isValidModuleDest(dir)) {
validFiles.push(name);
}
}
return validFiles;
}));
const versions = (0, (_map || _load_map()).default)();
for (const name of files) {
// check if folder starts with our prefix
if (name.indexOf(prefix) !== 0) {
continue;
}
const dir = path.join(cacheFolder, name);
// read manifest and validate correct name
const pkg = yield _this2.config.readManifest(dir, 'npm');
if (pkg.name !== _this2.name) {
continue;
}
// read package metadata
const metadata = yield _this2.config.readPackageMetadata(dir);
if (!metadata.remote) {
continue; // old yarn metadata
}
versions[pkg.version] = Object.assign({}, pkg, { _remote: metadata.remote });
}
const satisfied = yield _this2.config.resolveConstraints(Object.keys(versions), _this2.range);
if (satisfied) {
return versions[satisfied];
} else if (!_this2.config.preferOffline) {
throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('couldntFindPackageInCache', _this2.name, _this2.range, Object.keys(versions).join(', ')));
} else {
return null;
}
})();
}
cleanRegistry(url) {
Eif (this.config.getOption('registry') === (_constants || _load_constants()).YARN_REGISTRY) {
return url.replace(NPM_REGISTRY, (_constants || _load_constants()).YARN_REGISTRY);
} else {
return url;
}
}
resolve() {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// lockfile
const shrunk = _this3.request.getLocked('tarball');
Iif (shrunk) {
return shrunk;
}
const info = yield _this3.resolveRequest();
Iif (info == null) {
throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('packageNotFoundRegistry', _this3.name, 'npm'));
}
const deprecated = info.deprecated,
dist = info.dist;
Iif (typeof deprecated === 'string') {
let human = `${info.name}@${info.version}`;
const parentNames = _this3.request.getParentNames();
if (parentNames.length) {
human = parentNames.concat(human).join(' > ');
}
_this3.reporter.warn(`${human}: ${deprecated}`);
}
Eif (dist != null && dist.tarball) {
info._remote = {
resolved: `${_this3.cleanRegistry(dist.tarball)}#${dist.shasum}`,
type: 'tarball',
reference: _this3.cleanRegistry(dist.tarball),
hash: dist.shasum,
registry: 'npm'
};
}
info._uid = info.version;
return info;
})();
}
}
exports.default = NpmResolver;
NpmResolver.registry = 'npm';
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 1 1 1 1 1 199 199 199 199 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _baseResolver;
function _load_baseResolver() {
return _baseResolver = _interopRequireDefault(require('../base-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class RegistryResolver extends (_baseResolver || _load_baseResolver()).default {
constructor(request, name, range) {
super(request, `${name}@${range}`);
this.name = name;
this.range = range;
this.registryConfig = request.config.registries[this.constructor.registry].config;
}
}
exports.default = RegistryResolver;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _npmResolver;
function _load_npmResolver() {
return _npmResolver = _interopRequireDefault(require('./npm-resolver.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class YarnResolver extends (_npmResolver || _load_npmResolver()).default {}
exports.default = YarnResolver;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| blocking-queue.js | 87.69% | (57 / 65) | 75% | (27 / 36) | 90.91% | (10 / 11) | 87.5% | (56 / 64) | |
| child.js | 68.57% | (48 / 70) | 50% | (25 / 50) | 70% | (7 / 10) | 74.58% | (44 / 59) | |
| crypto.js | 93.75% | (15 / 16) | 66.67% | (4 / 6) | 80% | (4 / 5) | 93.75% | (15 / 16) | |
| env-replace.js | 53.85% | (7 / 13) | 25% | (4 / 16) | 100% | (1 / 1) | 53.85% | (7 / 13) | |
| execute-lifecycle-script.js | 81.75% | (112 / 137) | 60.71% | (51 / 84) | 85% | (17 / 20) | 85.83% | (109 / 127) | |
| filter.js | 37.31% | (25 / 67) | 23.53% | (12 / 51) | 50% | (2 / 4) | 37.31% | (25 / 67) | |
| fs.js | 61.11% | (275 / 450) | 46.07% | (123 / 267) | 65.22% | (45 / 69) | 61.82% | (272 / 440) | |
| git.js | 32.09% | (69 / 215) | 18.44% | (26 / 141) | 29.63% | (16 / 54) | 32.2% | (66 / 205) | |
| map.js | 100% | (13 / 13) | 92.31% | (12 / 13) | 100% | (1 / 1) | 100% | (13 / 13) | |
| misc.js | 92.86% | (39 / 42) | 66.67% | (8 / 12) | 100% | (7 / 7) | 92.86% | (39 / 42) | |
| network.js | 75% | (15 / 20) | 50% | (3 / 6) | 100% | (1 / 1) | 75% | (15 / 20) | |
| promise.js | 88.46% | (46 / 52) | 93.75% | (15 / 16) | 77.78% | (7 / 9) | 88.46% | (46 / 52) | |
| request-manager.js | 65.66% | (130 / 198) | 56.2% | (77 / 137) | 63.16% | (12 / 19) | 67.74% | (126 / 186) | |
| stream.js | 68.29% | (28 / 41) | 85.71% | (6 / 7) | 50% | (3 / 6) | 70% | (28 / 40) | |
| user-home-dir.js | 100% | (6 / 6) | 75% | (3 / 4) | 100% | (0 / 0) | 100% | (6 / 6) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | 1 1 1 1 1 1 3 3 3 3 3 3 3 3 3 3 28 25 28 2 10 2 8 10 10 10 10 10 20 10 10 10 20 20 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('./map.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const debug = require('debug')('yarn');
class BlockingQueue {
constructor(alias) {
let maxConcurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity;
this.concurrencyQueue = [];
this.maxConcurrency = maxConcurrency;
this.runningCount = 0;
this.warnedStuck = false;
this.alias = alias;
this.first = true;
this.running = (0, (_map || _load_map()).default)();
this.queue = (0, (_map || _load_map()).default)();
this.stuckTick = this.stuckTick.bind(this);
}
stillActive() {
if (this.stuckTimer) {
clearTimeout(this.stuckTimer);
}
this.stuckTimer = setTimeout(this.stuckTick, 5000);
}
stuckTick() {
Iif (this.runningCount === 1) {
this.warnedStuck = true;
debug(`The ${JSON.stringify(this.alias)} blocking queue may be stuck. 5 seconds ` + `without any activity with 1 worker: ${Object.keys(this.running)[0]}`);
}
}
push(key, factory) {
if (this.first) {
this.first = false;
} else {
this.stillActive();
}
return new Promise((resolve, reject) => {
// we're already running so push ourselves to the queue
const queue = this.queue[key] = this.queue[key] || [];
queue.push({ factory, resolve, reject });
Eif (!this.running[key]) {
this.shift(key);
}
});
}
shift(key) {
if (this.running[key]) {
delete this.running[key];
this.runningCount--;
Iif (this.warnedStuck) {
this.warnedStuck = false;
debug(`${JSON.stringify(this.alias)} blocking queue finally resolved. Nothing to worry about.`);
}
}
const queue = this.queue[key];
if (!queue) {
return;
}
var _queue$shift = queue.shift();
const resolve = _queue$shift.resolve,
reject = _queue$shift.reject,
factory = _queue$shift.factory;
Eif (!queue.length) {
delete this.queue[key];
}
const next = () => {
this.shift(key);
this.shiftConcurrencyQueue();
};
const run = () => {
this.running[key] = true;
this.runningCount++;
factory().then(function (val) {
resolve(val);
next();
return null;
}).catch(function (err) {
reject(err);
next();
});
};
this.maybePushConcurrencyQueue(run);
}
maybePushConcurrencyQueue(run) {
Eif (this.runningCount < this.maxConcurrency) {
run();
} else {
this.concurrencyQueue.push(run);
}
}
shiftConcurrencyQueue() {
Eif (this.runningCount < this.maxConcurrency) {
const fn = this.concurrencyQueue.shift();
Iif (fn) {
fn();
}
}
}
}
exports.default = BlockingQueue;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 3 3 3 3 3 3 3 3 1 1 3 3 3 3 2 3 2 3 3 3 3 3 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.exec = exports.queue = undefined;
exports.spawn = spawn;
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _blockingQueue;
function _load_blockingQueue() {
return _blockingQueue = _interopRequireDefault(require('./blocking-queue.js'));
}
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _promise;
function _load_promise() {
return _promise = require('./promise.js');
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/* global child_process$spawnOpts */
const child = require('child_process');
const queue = exports.queue = new (_blockingQueue || _load_blockingQueue()).default('child', (_constants || _load_constants()).CHILD_CONCURRENCY);
// TODO: this uid check is kinda whack
let uid = 0;
const exec = exports.exec = (0, (_promise || _load_promise()).promisify)(child.exec);
function spawn(program, args) {
let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
let onData = arguments[3];
return queue.push(opts.cwd || String(++uid), () => new Promise((resolve, reject) => {
const proc = child.spawn(program, args, opts);
let processingDone = false;
let processClosed = false;
let err = null;
let stdout = '';
proc.on('error', err => {
if (err.code === 'ENOENT') {
reject(new (_errors || _load_errors()).MessageError(`Couldn't find the binary ${program}`));
} else {
reject(err);
}
});
function updateStdout(chunk) {
stdout += chunk;
if (onData) {
onData(chunk);
}
}
function finish() {
Iif (err) {
reject(err);
} else {
resolve(stdout.trim());
}
}
Iif (typeof opts.process === 'function') {
opts.process(proc, updateStdout, reject, function () {
if (processClosed) {
finish();
} else {
processingDone = true;
}
});
} else {
if (proc.stderr) {
proc.stderr.on('data', updateStdout);
}
if (proc.stdout) {
proc.stdout.on('data', updateStdout);
}
processingDone = true;
}
proc.on('close', code => {
Iif (code >= 1) {
// TODO make this output nicer
err = new (_errors || _load_errors()).SpawnError(['Command failed.', `Exit code: ${code}`, `Command: ${program}`, `Arguments: ${args.join(' ')}`, `Directory: ${opts.cwd || process.cwd()}`, `Output:\n${stdout.trim()}`].join('\n'));
err.EXIT_CODE = code;
}
Eif (processingDone || err) {
finish();
} else {
processClosed = true;
}
});
}));
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 1 1 1 1 1 3 3 7 7 7 441 441 441 7 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hash = hash;
const crypto = require('crypto');
const stream = require('stream');
function hash(content) {
let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'md5';
return crypto.createHash(type).update(content).digest('hex');
}
class HashStream extends stream.Transform {
constructor(options) {
super(options);
this._hash = crypto.createHash('sha1');
this._updated = false;
}
_transform(chunk, encoding, callback) {
this._updated = true;
this._hash.update(chunk);
callback(null, chunk);
}
getHash() {
return this._hash.digest('hex');
}
test(sum) {
return this._updated && sum === this.getHash();
}
}
exports.HashStream = HashStream;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 1 1 1 1 4 4 4 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = envReplace;
const ENV_EXPR = /(\\*)\$\{([^}]+)\}/g;
function envReplace(value) {
let env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.env;
Eif (typeof value !== 'string' || !value) {
return value;
}
return value.replace(ENV_EXPR, (match, esc, envVarName) => {
if (esc.length && esc.length % 2) {
return match;
}
if (undefined === env[envVarName]) {
throw new Error('Failed to replace env in config: ' + match);
}
return env[envVarName] || '';
});
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | 1 1 1 1 1 1 1 1 1 1 1 1 1 3 3 3 3 3 3 3 3 3 3 152 152 152 6 146 26 149 298 149 120 117 117 3 117 3 3 333 333 333 144 189 189 39 333 333 333 333 3 1 3 1 1 3 3 3 3 3 6 6 6 3 3 3 3 3 3 3 1 3 1 1 4 4 4 4 1 1 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.execCommand = exports.execFromManifest = exports.executeLifecycleScript = undefined;
var _extends2;
function _load_extends() {
return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
}
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let makeEnv = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, cwd, config) {
const env = Object.assign({}, process.env);
env.npm_lifecycle_event = stage;
env.npm_node_execpath = env.NODE || process.execPath;
env.npm_execpath = path.join(__dirname, '..', '..', 'bin', 'yarn.js');
// Set the env to production for npm compat if production mode.
// https://github.com/npm/npm/blob/30d75e738b9cb7a6a3f9b50e971adcbe63458ed3/lib/utils/lifecycle.js#L336
Iif (config.production) {
env.NODE_ENV = 'production';
}
// Note: npm_config_argv environment variable contains output of nopt - command-line
// parser used by npm. Since we use other parser, we just roughly emulate it's output. (See: #684)
env.npm_config_argv = JSON.stringify({ remain: [], cooked: [config.commandName], original: [config.commandName] });
// add npm_package_*
const manifest = yield config.maybeReadManifest(cwd);
Eif (manifest) {
const queue = [['', manifest]];
while (queue.length) {
var _queue$pop = queue.pop(),
_queue$pop2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_queue$pop, 2);
const key = _queue$pop2[0],
val = _queue$pop2[1];
if (key[0] === '_') {
continue;
}
if (typeof val === 'object') {
for (const subKey in val) {
const completeKey = [key, subKey].filter(function (part) {
return !!part;
}).join('_');
queue.push([completeKey, val[subKey]]);
}
} else if (IGNORE_MANIFEST_KEYS.indexOf(key) < 0) {
let cleanVal = String(val);
if (cleanVal.indexOf('\n') >= 0) {
cleanVal = JSON.stringify(cleanVal);
}
env[`npm_package_${key}`] = cleanVal;
}
}
}
// add npm_config_*
const keys = new Set([...Object.keys(config.registries.yarn.config), ...Object.keys(config.registries.npm.config)]);
for (const key of keys) {
Iif (key.match(/:_/) || IGNORE_CONFIG_KEYS.indexOf(key) >= 0) {
continue;
}
let val = config.getOption(key);
if (!val) {
val = '';
} else Iif (typeof val === 'number') {
val = '' + val;
} else if (typeof val !== 'string') {
val = JSON.stringify(val);
}
Iif (val.indexOf('\n') >= 0) {
val = JSON.stringify(val);
}
const cleanKey = key.replace(/^_+/, '');
const envKey = `npm_config_${cleanKey}`.replace(/[^a-zA-Z0-9_]/g, '_');
env[envKey] = val;
}
return env;
});
return function makeEnv(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
})();
let executeLifecycleScript = exports.executeLifecycleScript = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, config, cwd, cmd, spinner) {
// if we don't have a spinner then pipe everything to the terminal
const stdio = spinner ? undefined : 'inherit';
const env = yield makeEnv(stage, cwd, config);
// split up the path
const pathParts = (env[(_constants || _load_constants()).ENV_PATH_KEY] || '').split(path.delimiter);
// add node-gyp
pathParts.unshift(path.join(__dirname, '..', '..', 'bin', 'node-gyp-bin'));
// add .bin folders to PATH
for (const registry of Object.keys((_index || _load_index()).registries)) {
const binFolder = path.join(config.registries[registry].folder, '.bin');
pathParts.unshift(path.join(config.linkFolder, binFolder));
pathParts.unshift(path.join(cwd, binFolder));
}
// join path back together
env[(_constants || _load_constants()).ENV_PATH_KEY] = pathParts.join(path.delimiter);
// get shell
const conf = { windowsVerbatimArguments: false };
let sh = 'sh';
let shFlag = '-c';
Iif (process.platform === 'win32') {
// cmd or command.com
sh = process.env.comspec || 'cmd';
// d - Ignore registry AutoRun commands
// s - Strip " quote characters from command.
// c - Run Command and then terminate
shFlag = '/d /s /c';
// handle windows run scripts starting with a relative path
cmd = (0, (_fixCmdWinSlashes || _load_fixCmdWinSlashes()).fixCmdWinSlashes)(cmd);
// handle quotes properly in windows environments - https://github.com/nodejs/node/issues/5060
conf.windowsVerbatimArguments = true;
}
const stdout = yield (_child || _load_child()).spawn(sh, [shFlag, cmd], (0, (_extends2 || _load_extends()).default)({ cwd, env, stdio }, conf), function (data) {
if (spinner) {
const line = data.toString() // turn buffer into string
.trim() // trim whitespace
.split('\n') // split into lines
.pop() // use only the last line
.replace(/\t/g, ' '); // change tabs to spaces as they can interfere with the console
if (line) {
spinner.tick(line);
}
}
});
return { cwd, command: cmd, stdout };
});
return function executeLifecycleScript(_x4, _x5, _x6, _x7, _x8) {
return _ref2.apply(this, arguments);
};
})();
let execFromManifest = exports.execFromManifest = (() => {
var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, commandName, cwd) {
const pkg = yield config.maybeReadManifest(cwd);
Iif (!pkg || !pkg.scripts) {
return;
}
const cmd = pkg.scripts[commandName];
if (cmd) {
yield execCommand(commandName, config, cmd, cwd);
}
});
return function execFromManifest(_x9, _x10, _x11) {
return _ref3.apply(this, arguments);
};
})();
let execCommand = exports.execCommand = (() => {
var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, config, cmd, cwd) {
const reporter = config.reporter;
try {
reporter.command(cmd);
yield executeLifecycleScript(stage, config, cwd, cmd);
return Promise.resolve();
} catch (err) {
if (err instanceof (_errors || _load_errors()).SpawnError) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('commandFailed', err.EXIT_CODE));
} else {
throw err;
}
}
});
return function execCommand(_x12, _x13, _x14, _x15) {
return _ref4.apply(this, arguments);
};
})();
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _child;
function _load_child() {
return _child = _interopRequireWildcard(require('./child.js'));
}
var _index;
function _load_index() {
return _index = require('../resolvers/index.js');
}
var _fixCmdWinSlashes;
function _load_fixCmdWinSlashes() {
return _fixCmdWinSlashes = require('./fix-cmd-win-slashes.js');
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
const IGNORE_MANIFEST_KEYS = ['readme'];
// We treat these configs as internal, thus not expose them to process.env.
// This helps us avoid some gyp issues when building native modules.
// See https://github.com/yarnpkg/yarn/issues/2286.
const IGNORE_CONFIG_KEYS = ['lastUpdateCheck'];
exports.default = executeLifecycleScript;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 21 21 21 21 4 4 21 21 21 21 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sortFilter = sortFilter;
exports.matchesFilter = matchesFilter;
exports.ignoreLinesToRegex = ignoreLinesToRegex;
var _misc;
function _load_misc() {
return _misc = require('./misc.js');
}
const minimatch = require('minimatch');
const path = require('path');
const WHITESPACE_RE = /^\s+$/;
function sortFilter(files, filters) {
let keepFiles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
let possibleKeepFiles = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new Set();
let ignoreFiles = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : new Set();
for (const file of files) {
let keep = false;
// always keep a file if a ! pattern matches it
for (const filter of filters) {
if (filter.isNegation && matchesFilter(filter, file.basename, file.relative)) {
keep = true;
break;
}
}
//
if (keep) {
keepFiles.add(file.relative);
continue;
}
// otherwise don't keep it if a pattern matches it
keep = true;
for (const filter of filters) {
if (!filter.isNegation && matchesFilter(filter, file.basename, file.relative)) {
keep = false;
break;
}
}
if (keep) {
possibleKeepFiles.add(file.relative);
} else {
ignoreFiles.add(file.relative);
}
}
// exclude file
for (const file of possibleKeepFiles) {
const parts = path.dirname(file).split(path.sep);
while (parts.length) {
const folder = parts.join(path.sep);
if (ignoreFiles.has(folder)) {
ignoreFiles.add(file);
break;
}
parts.pop();
}
}
//
for (const file of possibleKeepFiles) {
if (!ignoreFiles.has(file)) {
keepFiles.add(file);
}
}
//
for (const file of keepFiles) {
const parts = path.dirname(file).split(path.sep);
while (parts.length) {
// deregister this folder from being ignored, any files inside
// will still be marked as ignored
ignoreFiles.delete(parts.join(path.sep));
parts.pop();
}
}
return { keepFiles, ignoreFiles };
}
function matchesFilter(filter, basename, loc) {
if (filter.base && filter.base !== '.') {
loc = path.relative(filter.base, loc);
}
return filter.regex.test(loc) || filter.regex.test(`/${loc}`) || filter.regex.test(basename);
}
function ignoreLinesToRegex(lines) {
let base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
return lines
// create regex
.map(line => {
// remove empty lines, comments, etc
Iif (line === '' || line === '!' || line[0] === '#' || WHITESPACE_RE.test(line)) {
return null;
}
let pattern = line;
let isNegation = false;
// hide the fact that it's a negation from minimatch since we'll handle this specifally
// ourselves
if (pattern[0] === '!') {
isNegation = true;
pattern = pattern.slice(1);
}
// remove trailing slash
pattern = (0, (_misc || _load_misc()).removeSuffix)(pattern, '/');
const regex = minimatch.makeRe(pattern, { nocase: true });
Eif (regex) {
return {
base,
isNegation,
regex
};
} else {
return null;
}
}).filter(Boolean);
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 | 1 1 1 1 1 1 1 1 1 5603 5603 5603 5603 5603 346 5257 5257 5257 461 5257 5182 5182 5182 5182 5182 4573 4573 5182 4288 4288 4288 894 894 444 444 444 5023 8 8 8 8 29 969 969 461 461 461 461 4213 4213 461 461 461 461 5430 5084 288 508 508 508 508 1 5603 1 1 1 173 173 1 1 1 1401 1401 1 1 205 167 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 38 1 1 1 1 1 1 1 1 1 508 1 1 1 508 508 508 1016 508 508 508 508 508 508 508 508 508 508 508 508 508 508 508 508 1 508 1 508 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 350 1 350 1 1 350 350 350 1 350 1 1 1 1 1 27 27 27 27 27 27 27 27 27 1 27 1 1 7 7 7 7 7 133 7 133 133 133 133 133 3 7 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 695 695 695 695 1 695 1 1 695 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.makeTempDir = exports.hardlinksWork = exports.writeFilePreservingEol = exports.getFileSizeOnDisk = exports.walk = exports.symlink = exports.find = exports.readJsonAndFile = exports.readJson = exports.readFileAny = exports.hardlinkBulk = exports.copyBulk = exports.link = exports.chmod = exports.lstat = exports.exists = exports.mkdirp = exports.unlink = exports.stat = exports.access = exports.rename = exports.readdir = exports.realpath = exports.readlink = exports.writeFile = exports.readFileBuffer = exports.lockQueue = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let buildActionsForCopy = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) {
//
let build = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) {
const src = data.src,
dest = data.dest;
const onFresh = data.onFresh || noop;
const onDone = data.onDone || noop;
files.add(dest);
if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {
// ignored file
return;
}
const srcStat = yield lstat(src);
let srcFiles;
if (srcStat.isDirectory()) {
srcFiles = yield readdir(src);
}
if (yield exists(dest)) {
const destStat = yield lstat(dest);
const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();
const bothFolders = srcStat.isDirectory() && destStat.isDirectory();
const bothFiles = srcStat.isFile() && destStat.isFile();
if (srcStat.mode !== destStat.mode) {
try {
yield access(dest, srcStat.mode);
} catch (err) {
// EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving
// us modes that aren't valid. investigate this, it's generally safe to proceed.
}
}
if (bothFiles && srcStat.size === destStat.size && +srcStat.mtime === +destStat.mtime) {
// we can safely assume this is the same file
onDone();
reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime));
return;
}
Iif (bothSymlinks) {
const srcReallink = yield readlink(src);
if (srcReallink === (yield readlink(dest))) {
// if both symlinks are the same then we can continue on
onDone();
reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));
return;
}
}
if (bothFolders) {
// mark files that aren't in this folder as possibly extraneous
const destFiles = yield readdir(dest);
invariant(srcFiles, 'src files not initialised');
for (const file of destFiles) {
if (srcFiles.indexOf(file) < 0) {
const loc = path.join(dest, file);
possibleExtraneous.add(loc);
Eif ((yield lstat(loc)).isDirectory()) {
for (const file of yield readdir(loc)) {
possibleExtraneous.add(path.join(loc, file));
}
}
}
}
}
}
Iif (srcStat.isSymbolicLink()) {
onFresh();
const linkname = yield readlink(src);
actions.push({
type: 'symlink',
dest,
linkname
});
onDone();
} else if (srcStat.isDirectory()) {
reporter.verbose(reporter.lang('verboseFileFolder', dest));
yield mkdirp(dest);
const destParts = dest.split(path.sep);
while (destParts.length) {
files.add(destParts.join(path.sep));
destParts.pop();
}
// push all files to queue
invariant(srcFiles, 'src files not initialised');
let remaining = srcFiles.length;
Iif (!remaining) {
onDone();
}
for (const file of srcFiles) {
queue.push({
onFresh,
src: path.join(src, file),
dest: path.join(dest, file),
onDone: function () {
if (--remaining === 0) {
onDone();
}
}
});
}
} else Eif (srcStat.isFile()) {
onFresh();
actions.push({
type: 'file',
src,
dest,
atime: srcStat.atime,
mtime: srcStat.mtime,
mode: srcStat.mode
});
onDone();
} else {
throw new Error(`unsure how to copy this: ${src}`);
}
});
return function build(_x5) {
return _ref2.apply(this, arguments);
};
})();
const artifactFiles = new Set(events.artifactFiles || []);
const files = new Set();
// initialise events
for (const item of queue) {
const onDone = item.onDone;
item.onDone = function () {
events.onProgress(item.dest);
if (onDone) {
onDone();
}
};
}
events.onStart(queue.length);
// start building actions
const actions = [];
// custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items
// at a time due to the requirement to push items onto the queue
while (queue.length) {
const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);
yield Promise.all(items.map(build));
}
// simulate the existence of some files to prevent considering them extraenous
for (const file of artifactFiles) {
if (possibleExtraneous.has(file)) {
reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));
possibleExtraneous.delete(file);
}
}
for (const loc of possibleExtraneous) {
if (files.has(loc)) {
possibleExtraneous.delete(loc);
}
}
return actions;
});
return function buildActionsForCopy(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
let buildActionsForHardlink = (() => {
var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) {
//
let build = (() => {
var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) {
const src = data.src,
dest = data.dest;
const onFresh = data.onFresh || noop;
const onDone = data.onDone || noop;
files.add(dest);
if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {
// ignored file
return;
}
const srcStat = yield lstat(src);
let srcFiles;
if (srcStat.isDirectory()) {
srcFiles = yield readdir(src);
}
const destExists = yield exists(dest);
if (destExists) {
const destStat = yield lstat(dest);
const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();
const bothFolders = srcStat.isDirectory() && destStat.isDirectory();
const bothFiles = srcStat.isFile() && destStat.isFile();
if (srcStat.mode !== destStat.mode) {
try {
yield access(dest, srcStat.mode);
} catch (err) {
// EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving
// us modes that aren't valid. investigate this, it's generally safe to proceed.
reporter.verbose(err);
}
}
// correct hardlink
if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) {
onDone();
reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino));
return;
}
if (bothSymlinks) {
const srcReallink = yield readlink(src);
if (srcReallink === (yield readlink(dest))) {
// if both symlinks are the same then we can continue on
onDone();
reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));
return;
}
}
if (bothFolders) {
// mark files that aren't in this folder as possibly extraneous
const destFiles = yield readdir(dest);
invariant(srcFiles, 'src files not initialised');
for (const file of destFiles) {
if (srcFiles.indexOf(file) < 0) {
const loc = path.join(dest, file);
possibleExtraneous.add(loc);
if ((yield lstat(loc)).isDirectory()) {
for (const file of yield readdir(loc)) {
possibleExtraneous.add(path.join(loc, file));
}
}
}
}
}
}
if (srcStat.isSymbolicLink()) {
onFresh();
const linkname = yield readlink(src);
actions.push({
type: 'symlink',
dest,
linkname
});
onDone();
} else if (srcStat.isDirectory()) {
reporter.verbose(reporter.lang('verboseFileFolder', dest));
yield mkdirp(dest);
const destParts = dest.split(path.sep);
while (destParts.length) {
files.add(destParts.join(path.sep));
destParts.pop();
}
// push all files to queue
invariant(srcFiles, 'src files not initialised');
let remaining = srcFiles.length;
if (!remaining) {
onDone();
}
for (const file of srcFiles) {
queue.push({
onFresh,
src: path.join(src, file),
dest: path.join(dest, file),
onDone: function () {
if (--remaining === 0) {
onDone();
}
}
});
}
} else if (srcStat.isFile()) {
onFresh();
actions.push({
type: 'link',
src,
dest,
removeDest: destExists
});
onDone();
} else {
throw new Error(`unsure how to copy this: ${src}`);
}
});
return function build(_x10) {
return _ref4.apply(this, arguments);
};
})();
const artifactFiles = new Set(events.artifactFiles || []);
const files = new Set();
// initialise events
for (const item of queue) {
const onDone = item.onDone;
item.onDone = function () {
events.onProgress(item.dest);
if (onDone) {
onDone();
}
};
}
events.onStart(queue.length);
// start building actions
const actions = [];
// custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items
// at a time due to the requirement to push items onto the queue
while (queue.length) {
const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);
yield Promise.all(items.map(build));
}
// simulate the existence of some files to prevent considering them extraenous
for (const file of artifactFiles) {
if (possibleExtraneous.has(file)) {
reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));
possibleExtraneous.delete(file);
}
}
for (const loc of possibleExtraneous) {
Iif (files.has(loc)) {
possibleExtraneous.delete(loc);
}
}
return actions;
});
return function buildActionsForHardlink(_x6, _x7, _x8, _x9) {
return _ref3.apply(this, arguments);
};
})();
let copyBulk = exports.copyBulk = (() => {
var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) {
const events = {
onStart: _events && _events.onStart || noop,
onProgress: _events && _events.onProgress || noop,
possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),
ignoreBasenames: _events && _events.ignoreBasenames || [],
artifactFiles: _events && _events.artifactFiles || []
};
const actions = yield buildActionsForCopy(queue, events, events.possibleExtraneous, reporter);
events.onStart(actions.length);
const fileActions = actions.filter(function (action) {
return action.type === 'file';
});
const currentlyWriting = {};
yield (_promise || _load_promise()).queue(fileActions, (() => {
var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) {
let writePromise;
while (writePromise = currentlyWriting[data.dest]) {
yield writePromise;
}
const cleanup = function () {
return delete currentlyWriting[data.dest];
};
return currentlyWriting[data.dest] = new Promise(function (resolve, reject) {
const readStream = fs.createReadStream(data.src);
const writeStream = fs.createWriteStream(data.dest, { mode: data.mode });
reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest));
readStream.on('error', reject);
writeStream.on('error', reject);
writeStream.on('open', function () {
readStream.pipe(writeStream);
});
writeStream.once('finish', function () {
fs.utimes(data.dest, data.atime, data.mtime, function (err) {
Iif (err) {
reject(err);
} else {
events.onProgress(data.dest);
cleanup();
resolve();
}
});
});
}).then(function (arg) {
cleanup();
return arg;
}).catch(function (arg) {
cleanup();
throw arg;
});
});
return function (_x14) {
return _ref6.apply(this, arguments);
};
})(), CONCURRENT_QUEUE_ITEMS);
// we need to copy symlinks last as they could reference files we were copying
const symlinkActions = actions.filter(function (action) {
return action.type === 'symlink';
});
yield (_promise || _load_promise()).queue(symlinkActions, function (data) {
const linkname = path.resolve(path.dirname(data.dest), data.linkname);
reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));
return symlink(linkname, data.dest);
});
});
return function copyBulk(_x11, _x12, _x13) {
return _ref5.apply(this, arguments);
};
})();
let hardlinkBulk = exports.hardlinkBulk = (() => {
var _ref7 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) {
const events = {
onStart: _events && _events.onStart || noop,
onProgress: _events && _events.onProgress || noop,
possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),
artifactFiles: _events && _events.artifactFiles || [],
ignoreBasenames: []
};
const actions = yield buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter);
events.onStart(actions.length);
const fileActions = actions.filter(function (action) {
return action.type === 'link';
});
yield (_promise || _load_promise()).queue(fileActions, (() => {
var _ref8 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) {
reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest));
if (data.removeDest) {
yield unlink(data.dest);
}
yield link(data.src, data.dest);
});
return function (_x18) {
return _ref8.apply(this, arguments);
};
})(), CONCURRENT_QUEUE_ITEMS);
// we need to copy symlinks last as they could reference files we were copying
const symlinkActions = actions.filter(function (action) {
return action.type === 'symlink';
});
yield (_promise || _load_promise()).queue(symlinkActions, function (data) {
const linkname = path.resolve(path.dirname(data.dest), data.linkname);
reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));
return symlink(linkname, data.dest);
});
});
return function hardlinkBulk(_x15, _x16, _x17) {
return _ref7.apply(this, arguments);
};
})();
let readFileAny = exports.readFileAny = (() => {
var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (files) {
for (const file of files) {
if (yield exists(file)) {
return readFile(file);
}
}
return null;
});
return function readFileAny(_x19) {
return _ref9.apply(this, arguments);
};
})();
let readJson = exports.readJson = (() => {
var _ref10 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) {
return (yield readJsonAndFile(loc)).object;
});
return function readJson(_x20) {
return _ref10.apply(this, arguments);
};
})();
let readJsonAndFile = exports.readJsonAndFile = (() => {
var _ref11 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) {
const file = yield readFile(loc);
try {
return {
object: (0, (_map || _load_map()).default)(JSON.parse(stripBOM(file))),
content: file
};
} catch (err) {
err.message = `${loc}: ${err.message}`;
throw err;
}
});
return function readJsonAndFile(_x21) {
return _ref11.apply(this, arguments);
};
})();
let find = exports.find = (() => {
var _ref12 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (filename, dir) {
const parts = dir.split(path.sep);
while (parts.length) {
const loc = parts.concat(filename).join(path.sep);
if (yield exists(loc)) {
return loc;
} else {
parts.pop();
}
}
return false;
});
return function find(_x22, _x23) {
return _ref12.apply(this, arguments);
};
})();
let symlink = exports.symlink = (() => {
var _ref13 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) {
try {
const stats = yield lstat(dest);
if (stats.isSymbolicLink() && (yield exists(dest))) {
const resolved = yield realpath(dest);
if (resolved === src) {
return;
}
}
yield unlink(dest);
} catch (err) {
Iif (err.code !== 'ENOENT') {
throw err;
}
}
try {
Iif (process.platform === 'win32') {
// use directory junctions if possible on win32, this requires absolute paths
yield fsSymlink(src, dest, 'junction');
} else {
// use relative paths otherwise which will be retained if the directory is moved
let relative;
Eif (yield exists(src)) {
relative = path.relative(fs.realpathSync(path.dirname(dest)), fs.realpathSync(src));
} else {
relative = path.relative(path.dirname(dest), src);
}
yield fsSymlink(relative, dest);
}
} catch (err) {
if (err.code === 'EEXIST') {
// race condition
yield symlink(src, dest);
} else {
throw err;
}
}
});
return function symlink(_x24, _x25) {
return _ref13.apply(this, arguments);
};
})();
let walk = exports.walk = (() => {
var _ref14 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir, relativeDir) {
let ignoreBasenames = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
let files = [];
let filenames = yield readdir(dir);
Eif (ignoreBasenames.size) {
filenames = filenames.filter(function (name) {
return !ignoreBasenames.has(name);
});
}
for (const name of filenames) {
const relative = relativeDir ? path.join(relativeDir, name) : name;
const loc = path.join(dir, name);
const stat = yield lstat(loc);
files.push({
relative,
basename: name,
absolute: loc,
mtime: +stat.mtime
});
if (stat.isDirectory()) {
files = files.concat((yield walk(loc, relative, ignoreBasenames)));
}
}
return files;
});
return function walk(_x26, _x27) {
return _ref14.apply(this, arguments);
};
})();
let getFileSizeOnDisk = exports.getFileSizeOnDisk = (() => {
var _ref15 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) {
const stat = yield lstat(loc);
const size = stat.size,
blockSize = stat.blksize;
return Math.ceil(size / blockSize) * blockSize;
});
return function getFileSizeOnDisk(_x29) {
return _ref15.apply(this, arguments);
};
})();
let getEolFromFile = (() => {
var _ref16 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path) {
Eif (!(yield exists(path))) {
return undefined;
}
const buffer = yield readFileBuffer(path);
for (let i = 0; i < buffer.length; ++i) {
if (buffer[i] === cr) {
return '\r\n';
}
if (buffer[i] === lf) {
return '\n';
}
}
return undefined;
});
return function getEolFromFile(_x30) {
return _ref16.apply(this, arguments);
};
})();
let writeFilePreservingEol = exports.writeFilePreservingEol = (() => {
var _ref17 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path, data) {
const eol = (yield getEolFromFile(path)) || os.EOL;
Iif (eol !== '\n') {
data = data.replace(/\n/g, eol);
}
yield (0, (_promise2 || _load_promise2()).promisify)(fs.writeFile)(path, data);
});
return function writeFilePreservingEol(_x31, _x32) {
return _ref17.apply(this, arguments);
};
})();
let hardlinksWork = exports.hardlinksWork = (() => {
var _ref18 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir) {
const filename = 'test-file' + Math.random();
const file = path.join(dir, filename);
const fileLink = path.join(dir, filename + '-link');
try {
yield writeFile(file, 'test');
yield link(file, fileLink);
} catch (err) {
return false;
} finally {
yield unlink(file);
yield unlink(fileLink);
}
return true;
});
return function hardlinksWork(_x33) {
return _ref18.apply(this, arguments);
};
})();
// not a strict polyfill for Node's fs.mkdtemp
let makeTempDir = exports.makeTempDir = (() => {
var _ref19 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (prefix) {
const dir = path.join(os.tmpdir(), `yarn-${prefix || ''}-${Date.now()}-${Math.random()}`);
yield unlink(dir);
yield mkdirp(dir);
return dir;
});
return function makeTempDir(_x34) {
return _ref19.apply(this, arguments);
};
})();
exports.copy = copy;
exports.readFile = readFile;
exports.readFileRaw = readFileRaw;
exports.normalizeOS = normalizeOS;
var _blockingQueue;
function _load_blockingQueue() {
return _blockingQueue = _interopRequireDefault(require('./blocking-queue.js'));
}
var _promise;
function _load_promise() {
return _promise = _interopRequireWildcard(require('./promise.js'));
}
var _promise2;
function _load_promise2() {
return _promise2 = require('./promise.js');
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('./map.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
const fs = require('fs');
const os = require('os');
const lockQueue = exports.lockQueue = new (_blockingQueue || _load_blockingQueue()).default('fs lock');
const readFileBuffer = exports.readFileBuffer = (0, (_promise2 || _load_promise2()).promisify)(fs.readFile);
const writeFile = exports.writeFile = (0, (_promise2 || _load_promise2()).promisify)(fs.writeFile);
const readlink = exports.readlink = (0, (_promise2 || _load_promise2()).promisify)(fs.readlink);
const realpath = exports.realpath = (0, (_promise2 || _load_promise2()).promisify)(fs.realpath);
const readdir = exports.readdir = (0, (_promise2 || _load_promise2()).promisify)(fs.readdir);
const rename = exports.rename = (0, (_promise2 || _load_promise2()).promisify)(fs.rename);
const access = exports.access = (0, (_promise2 || _load_promise2()).promisify)(fs.access);
const stat = exports.stat = (0, (_promise2 || _load_promise2()).promisify)(fs.stat);
const unlink = exports.unlink = (0, (_promise2 || _load_promise2()).promisify)(require('rimraf'));
const mkdirp = exports.mkdirp = (0, (_promise2 || _load_promise2()).promisify)(require('mkdirp'));
const exists = exports.exists = (0, (_promise2 || _load_promise2()).promisify)(fs.exists, true);
const lstat = exports.lstat = (0, (_promise2 || _load_promise2()).promisify)(fs.lstat);
const chmod = exports.chmod = (0, (_promise2 || _load_promise2()).promisify)(fs.chmod);
const link = exports.link = (0, (_promise2 || _load_promise2()).promisify)(fs.link);
const CONCURRENT_QUEUE_ITEMS = 4;
const fsSymlink = (0, (_promise2 || _load_promise2()).promisify)(fs.symlink);
const invariant = require('invariant');
const stripBOM = require('strip-bom');
const noop = () => {};
function copy(src, dest, reporter) {
return copyBulk([{ src, dest }], reporter);
}
function _readFile(loc, encoding) {
return new Promise((resolve, reject) => {
fs.readFile(loc, encoding, function (err, content) {
Iif (err) {
reject(err);
} else {
resolve(content);
}
});
});
}
function readFile(loc) {
return _readFile(loc, 'utf8').then(normalizeOS);
}
function readFileRaw(loc) {
return _readFile(loc, 'binary');
}
function normalizeOS(body) {
return body.replace(/\r\n/g, '\n');
}
const cr = new Buffer('\r', 'utf8')[0];
const lf = new Buffer('\n', 'utf8')[0];
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 80 2 2 2 2 2 2 2 2 2 2 2 2 2 80 80 80 80 80 2 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _misc;
function _load_misc() {
return _misc = require('./misc.js');
}
var _crypto;
function _load_crypto() {
return _crypto = _interopRequireWildcard(require('./crypto.js'));
}
var _child;
function _load_child() {
return _child = _interopRequireWildcard(require('./child.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('./fs.js'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('./map.js'));
}
var _fs2;
function _load_fs2() {
return _fs2 = require('fs');
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const invariant = require('invariant');
const semver = require('semver');
const url = require('url');
const tar = require('tar');
const supportsArchiveCache = (0, (_map || _load_map()).default)({
'github.com': false });
class Git {
constructor(config, url, hash) {
this.supportsArchive = false;
this.fetched = false;
this.config = config;
this.reporter = config.reporter;
this.hash = hash;
this.ref = hash;
this.url = Git.cleanUrl(url);
this.cwd = this.config.getTemp((_crypto || _load_crypto()).hash(this.url));
}
static cleanUrl(url) {
return url.replace(/^git\+/, '');
}
/**
* Check if the host specified in the input `gitUrl` has archive capability.
*/
static hasArchiveCapability(gitUrl) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// USER@HOSTNAME:PATHNAME
const match = gitUrl.match(/^(.*?)@(.*?):(.*?)$/);
if (!match) {
return false;
}
var _match = (0, (_slicedToArray2 || _load_slicedToArray()).default)(match, 3);
const hostname = _match[2];
const cached = supportsArchiveCache[hostname];
if (cached != null) {
return cached;
}
try {
yield (_child || _load_child()).spawn('git', ['archive', `--remote=${gitUrl}`, 'HEAD', Date.now() + '']);
throw new Error();
} catch (err) {
const supports = err.message.indexOf('did not match any files') >= 0;
return supportsArchiveCache[hostname] = supports;
}
})();
}
/**
* Check if the input `target` is a 5-40 character hex commit hash.
*/
static isCommitHash(target) {
return !!target && /^[a-f0-9]{5,40}$/.test(target);
}
static repoExists(gitUrl) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
try {
yield (_child || _load_child()).spawn('git', ['ls-remote', '-t', gitUrl]);
return true;
} catch (err) {
return false;
}
})();
}
/**
* Attempt to upgrade insecure protocols to secure protocol
*/
static secureUrl(ref, hash, reporter) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (Git.isCommitHash(hash)) {
// this is cryptographically secure
return ref;
}
const parts = url.parse(ref);
if (parts.protocol === 'git:') {
const secureUrl = ref.replace(/^git:/, 'https:');
if (yield Git.repoExists(secureUrl)) {
return secureUrl;
} else {
throw new (_errors || _load_errors()).SecurityError(reporter.lang('refusingDownloadGitWithoutCommit', ref));
}
}
if (parts.protocol === 'http:') {
const secureUrl = ref.replace(/^http:/, 'https:');
if (yield Git.repoExists(secureUrl)) {
return secureUrl;
} else {
if (yield Git.repoExists(ref)) {
return ref;
} else {
throw new (_errors || _load_errors()).SecurityError(reporter.lang('refusingDownloadHTTPWithoutCommit', ref));
}
}
}
if (parts.protocol === 'https:') {
if (yield Git.repoExists(ref)) {
return ref;
} else {
throw new (_errors || _load_errors()).SecurityError(reporter.lang('refusingDownloadHTTPSWithoutCommit', ref));
}
}
return ref;
})();
}
/**
* Archive a repo to destination
*/
archive(dest) {
if (this.supportsArchive) {
return this._archiveViaRemoteArchive(dest);
} else {
return this._archiveViaLocalFetched(dest);
}
}
_archiveViaRemoteArchive(dest) {
var _this = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const hashStream = new (_crypto || _load_crypto()).HashStream();
yield (_child || _load_child()).spawn('git', ['archive', `--remote=${_this.url}`, _this.ref], {
process(proc, resolve, reject, done) {
const writeStream = (0, (_fs2 || _load_fs2()).createWriteStream)(dest);
proc.on('error', reject);
writeStream.on('error', reject);
writeStream.on('end', done);
writeStream.on('open', function () {
proc.stdout.pipe(hashStream).pipe(writeStream);
});
writeStream.once('finish', done);
}
});
return hashStream.getHash();
})();
}
_archiveViaLocalFetched(dest) {
var _this2 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const hashStream = new (_crypto || _load_crypto()).HashStream();
yield (_child || _load_child()).spawn('git', ['archive', _this2.hash], {
cwd: _this2.cwd,
process(proc, resolve, reject, done) {
const writeStream = (0, (_fs2 || _load_fs2()).createWriteStream)(dest);
proc.on('error', reject);
writeStream.on('error', reject);
writeStream.on('open', function () {
proc.stdout.pipe(hashStream).pipe(writeStream);
});
writeStream.once('finish', done);
}
});
return hashStream.getHash();
})();
}
/**
* Clone a repo to the input `dest`. Use `git archive` if it's available, otherwise fall
* back to `git clone`.
*/
clone(dest) {
if (this.supportsArchive) {
return this._cloneViaRemoteArchive(dest);
} else {
return this._cloneViaLocalFetched(dest);
}
}
_cloneViaRemoteArchive(dest) {
var _this3 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield (_child || _load_child()).spawn('git', ['archive', `--remote=${_this3.url}`, _this3.ref], {
process(proc, update, reject, done) {
const extractor = tar.Extract({ path: dest });
extractor.on('error', reject);
extractor.on('end', done);
proc.stdout.pipe(extractor);
proc.on('error', reject);
}
});
})();
}
_cloneViaLocalFetched(dest) {
var _this4 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield (_child || _load_child()).spawn('git', ['archive', _this4.hash], {
cwd: _this4.cwd,
process(proc, resolve, reject, done) {
const extractor = tar.Extract({ path: dest });
extractor.on('error', reject);
extractor.on('end', done);
proc.stdout.pipe(extractor);
}
});
})();
}
/**
* Clone this repo.
*/
fetch() {
var _this5 = this;
const url = this.url,
cwd = this.cwd;
return (_fs || _load_fs()).lockQueue.push(url, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
if (yield (_fs || _load_fs()).exists(cwd)) {
yield (_child || _load_child()).spawn('git', ['pull'], { cwd });
} else {
yield (_child || _load_child()).spawn('git', ['clone', url, cwd]);
}
_this5.fetched = true;
}));
}
/**
* Given a list of tags/branches from git, check if they match an input range.
*/
findResolution(range, tags) {
var _this6 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// If there are no tags and target is *, fallback to the latest commit on master
// or if we have no target.
Iif (!range || !tags.length && range === '*') {
return 'master';
}
return (yield _this6.config.resolveConstraints(tags.filter(function (tag) {
return !!semver.valid(tag, _this6.config.looseSemver);
}), range)) || range;
})();
}
/**
* Fetch the file by cloning the repo and reading it.
*/
getFile(filename) {
if (this.supportsArchive) {
return this._getFileFromArchive(filename);
} else {
return this._getFileFromClone(filename);
}
}
_getFileFromArchive(filename) {
var _this7 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
try {
return yield (_child || _load_child()).spawn('git', ['archive', `--remote=${_this7.url}`, _this7.ref, filename], {
process(proc, update, reject, done) {
const parser = tar.Parse();
parser.on('error', reject);
parser.on('end', done);
parser.on('data', entry => {
update(entry.toString());
});
proc.stdout.pipe(parser);
}
});
} catch (err) {
if (err.message.indexOf('did not match any files') >= 0) {
return false;
} else {
throw err;
}
}
})();
}
_getFileFromClone(filename) {
var _this8 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
invariant(_this8.fetched, 'Repo not fetched');
try {
return yield (_child || _load_child()).spawn('git', ['show', `${_this8.hash}:${filename}`], { cwd: _this8.cwd });
} catch (err) {
// file doesn't exist
return false;
}
})();
}
/**
* Initialize the repo, find a secure url to use and
* set the ref to match an input `target`.
*/
init() {
var _this9 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
_this9.url = yield Git.secureUrl(_this9.url, _this9.hash, _this9.reporter);
// check capabilities
if (yield Git.hasArchiveCapability(_this9.url)) {
_this9.supportsArchive = true;
} else {
yield _this9.fetch();
}
return yield _this9.setRefRemote();
})();
}
setRefRemote() {
var _this10 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const stdout = yield (_child || _load_child()).spawn('git', ['ls-remote', '--tags', '--heads', _this10.url]);
const refs = Git.parseRefs(stdout);
return yield _this10.setRef(refs);
})();
}
/**
* TODO description
*/
setRef(refs) {
var _this11 = this;
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
// get commit ref
const hash = _this11.hash;
const names = Object.keys(refs);
Iif (Git.isCommitHash(hash)) {
for (const name in refs) {
if (refs[name] === hash) {
_this11.ref = name;
return hash;
}
}
// `git archive` only accepts a treeish and we have no ref to this commit
_this11.supportsArchive = false;
if (!_this11.fetched) {
// in fact, `git archive` can't be used, and we haven't fetched the project yet. Do it now.
yield _this11.fetch();
}
return _this11.ref = _this11.hash = hash;
}
const ref = yield _this11.findResolution(hash, names);
const commit = refs[ref];
Eif (commit) {
_this11.ref = ref;
return _this11.hash = commit;
} else {
throw new (_errors || _load_errors()).MessageError(_this11.reporter.lang('couldntFindMatch', ref, names.join(','), _this11.url));
}
})();
}
/**
* TODO description
*/
static parseRefs(stdout) {
// store references
const refs = {};
// line delimited
const refLines = stdout.split('\n');
for (const line of refLines) {
// line example: 64b2c0cee9e829f73c5ad32b8cc8cb6f3bec65bb refs/tags/v4.2.2
var _line$split = line.split(/\s+/g),
_line$split2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_line$split, 2);
const sha = _line$split2[0],
id = _line$split2[1];
let name = id.split('/').slice(2).join('/');
// TODO: find out why this is necessary. idk it makes it work...
name = (0, (_misc || _load_misc()).removeSuffix)(name, '^{}');
refs[name] = sha;
}
return refs;
}
}
exports.default = Git;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 1 1 1 7377 7377 464 1437 6913 1356 1356 1356 5572 7377 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = nullify;
function nullify() {
let obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (Array.isArray(obj)) {
for (const item of obj) {
nullify(item);
}
} else if (obj !== null && typeof obj === 'object' || typeof obj === 'function') {
Object.setPrototypeOf(obj, null);
// for..in can only be applied to 'object', not 'function'
Eif (typeof obj === 'object') {
for (const key in obj) {
nullify(obj[key]);
}
}
}
return obj;
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | 1 1 1 1 1 1 1 1 1 1 5097 5097 9251 9251 9251 5072 25 1 703 703 703 5537 703 1 312 305 312 1 101 101 1 206 206 1 33 4 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sortAlpha = sortAlpha;
exports.entries = entries;
exports.removePrefix = removePrefix;
exports.removeSuffix = removeSuffix;
exports.addSuffix = addSuffix;
exports.hyphenate = hyphenate;
exports.camelCase = camelCase;
const _camelCase = require('camelcase');
function sortAlpha(a, b) {
// sort alphabetically in a deterministic way
const shortLen = Math.min(a.length, b.length);
for (let i = 0; i < shortLen; i++) {
const aChar = a.charCodeAt(i);
const bChar = b.charCodeAt(i);
if (aChar !== bChar) {
return aChar - bChar;
}
}
return a.length - b.length;
}
function entries(obj) {
const entries = [];
Eif (obj) {
for (const key in obj) {
entries.push([key, obj[key]]);
}
}
return entries;
}
function removePrefix(pattern, prefix) {
if (pattern.startsWith(prefix)) {
pattern = pattern.slice(prefix.length);
}
return pattern;
}
function removeSuffix(pattern, suffix) {
Iif (pattern.endsWith(suffix)) {
return pattern.slice(0, -suffix.length);
}
return pattern;
}
function addSuffix(pattern, suffix) {
Iif (!pattern.endsWith(suffix)) {
return pattern + suffix;
}
return pattern;
}
function hyphenate(str) {
return str.replace(/[A-Z]/g, match => {
return '-' + match.charAt(0).toLowerCase();
});
}
function camelCase(str) {
Iif (/[A-Z]/.test(str)) {
return null;
} else {
return _camelCase(str);
}
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 1 1 1 1 1 1 2 2 2 2 4 4 4 4 2 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isOffline = isOffline;
const os = require('os');
const IGNORE_INTERFACES = ['lo0', 'awdl0', 'bridge0'];
const LOCAL_IPS = ['127.0.0.1', '::1'];
function isOffline() {
let interfaces;
try {
interfaces = os.networkInterfaces();
} catch (e) {
// As of October 2016, Windows Subsystem for Linux (WSL) does not support
// the os.networkInterfaces() call and throws instead. For this platform,
// assume we are online.
if (e.syscall === 'uv_interface_addresses') {
return false;
} else {
throw e;
}
}
for (const name in interfaces) {
Iif (IGNORE_INTERFACES.indexOf(name) >= 0) {
continue;
}
const addrs = interfaces[name];
for (const addr of addrs) {
if (LOCAL_IPS.indexOf(addr.address) < 0) {
// found a possible remote ip
return false;
}
}
}
return true;
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | 1 1 1 1 1 1 1 18 23520 28157 23520 23520 23520 12742 23520 23520 23520 23520 6068 6068 23520 4600 18920 23520 1 1 7 7 7 7 7 7 3 4 4 19 1 857 857 857 857 857 857 4 853 838 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.wait = wait;
exports.promisify = promisify;
exports.promisifyObject = promisifyObject;
exports.queue = queue;
function wait(delay) {
return new Promise(resolve => {
setTimeout(resolve, delay);
});
}
function promisify(fn, firstData) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return new Promise(function (resolve, reject) {
args.push(function (err) {
for (var _len2 = arguments.length, result = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
result[_key2 - 1] = arguments[_key2];
}
let res = result;
Eif (result.length <= 1) {
res = result[0];
}
if (firstData) {
res = err;
err = null;
}
if (err) {
reject(err);
} else {
resolve(res);
}
});
fn.apply(null, args);
});
};
}
function promisifyObject(obj) {
const promisedObj = {};
for (const key in obj) {
promisedObj[key] = promisify(obj[key]);
}
return promisedObj;
}
function queue(arr, promiseProducer) {
let concurrency = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Infinity;
concurrency = Math.min(concurrency, arr.length);
// clone
arr = arr.slice();
const results = [];
let total = arr.length;
if (!total) {
return Promise.resolve(results);
}
return new Promise((resolve, reject) => {
for (let i = 0; i < concurrency; i++) {
next();
}
function next() {
const item = arr.shift();
const promise = promiseProducer(item);
promise.then(function (result) {
results.push(result);
total--;
if (total === 0) {
resolve(results);
} else {
if (arr.length) {
next();
}
}
}, reject);
}
});
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 3 2 3 2 3 1 3 1 3 1 3 3 1 3 3 1 3 1 181 1 1 1 181 212 212 212 31 181 181 181 181 181 181 181 181 181 174 181 1 1 181 181 362 181 181 181 181 181 181 181 181 181 174 174 174 174 174 174 174 174 174 181 7 181 181 181 181 181 181 181 181 181 181 181 181 181 181 181 6 181 7 362 181 181 181 181 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _errors;
function _load_errors() {
return _errors = require('../errors.js');
}
var _blockingQueue;
function _load_blockingQueue() {
return _blockingQueue = _interopRequireDefault(require('./blocking-queue.js'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireWildcard(require('../constants.js'));
}
var _network;
function _load_network() {
return _network = _interopRequireWildcard(require('./network.js'));
}
var _map;
function _load_map() {
return _map = _interopRequireDefault(require('../util/map.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const RequestCaptureHar = require('request-capture-har');
const invariant = require('invariant');
const url = require('url');
const fs = require('fs');
const successHosts = (0, (_map || _load_map()).default)();
const controlOffline = (_network || _load_network()).isOffline();
class RequestManager {
constructor(reporter) {
this.offlineNoRequests = false;
this._requestCaptureHar = null;
this._requestModule = null;
this.offlineQueue = [];
this.captureHar = false;
this.httpsProxy = null;
this.ca = null;
this.httpProxy = null;
this.strictSSL = true;
this.userAgent = '';
this.reporter = reporter;
this.running = 0;
this.queue = [];
this.cache = {};
this.max = (_constants || _load_constants()).NETWORK_CONCURRENCY;
}
setOptions(opts) {
if (opts.userAgent != null) {
this.userAgent = opts.userAgent;
}
if (opts.offline != null) {
this.offlineNoRequests = opts.offline;
}
if (opts.captureHar != null) {
this.captureHar = opts.captureHar;
}
if (opts.httpProxy != null) {
this.httpProxy = opts.httpProxy;
}
if (opts.httpsProxy != null) {
this.httpsProxy = opts.httpsProxy;
}
if (opts.strictSSL !== null && typeof opts.strictSSL !== 'undefined') {
this.strictSSL = opts.strictSSL;
}
Iif (opts.ca != null && opts.ca.length > 0) {
this.ca = opts.ca;
}
if (opts.networkConcurrency != null) {
this.max = opts.networkConcurrency;
}
Iif (opts.cafile != null && opts.cafile != '') {
// The CA bundle file can contain one or more certificates with comments/text between each PEM block.
// tls.connect wants an array of certificates without any comments/text, so we need to split the string
// and strip out any text in between the certificates
try {
const bundle = fs.readFileSync(opts.cafile).toString();
const hasPemPrefix = block => block.startsWith('-----BEGIN ');
// opts.cafile overrides opts.ca, this matches with npm behavior
this.ca = bundle.split(/(-----BEGIN .*\r?\n[^-]+\r?\n--.*)/).filter(hasPemPrefix);
} catch (err) {
this.reporter.error(`Could not open cafile: ${err.message}`);
}
}
if (opts.cert != null) {
this.cert = opts.cert;
}
if (opts.key != null) {
this.key = opts.key;
}
}
/**
* Lazy load `request` since it is exceptionally expensive to load and is
* often not needed at all.
*/
_getRequestModule() {
if (!this._requestModule) {
const request = require('request');
Iif (this.captureHar) {
this._requestCaptureHar = new RequestCaptureHar(request);
this._requestModule = this._requestCaptureHar.request.bind(this._requestCaptureHar);
} else {
this._requestModule = request;
}
}
return this._requestModule;
}
/**
* Queue up a request.
*/
request(params) {
Iif (this.offlineNoRequests) {
return Promise.reject(new (_errors || _load_errors()).MessageError(this.reporter.lang('cantRequestOffline')));
}
const cached = this.cache[params.url];
if (cached) {
return cached;
}
params.method = params.method || 'GET';
params.forever = true;
params.retryAttempts = 0;
params.strictSSL = this.strictSSL;
params.headers = Object.assign({
'User-Agent': this.userAgent
}, params.headers);
const promise = new Promise((resolve, reject) => {
this.queue.push({ params, resolve, reject });
this.shiftQueue();
});
// we can't cache a request with a processor
if (!params.process) {
this.cache[params.url] = promise;
}
return promise;
}
/**
* Clear the request cache. This is important as we cache all HTTP requests so you'll
* want to do this as soon as you can.
*/
clearCache() {
this.cache = {};
Iif (this._requestCaptureHar != null) {
this._requestCaptureHar.clear();
}
}
/**
* Check if an error is possibly due to lost or poor network connectivity.
*/
isPossibleOfflineError(err) {
const code = err.code,
hostname = err.hostname;
if (!code) {
return false;
}
// network was previously online but now we're offline
const possibleOfflineChange = !controlOffline && !(_network || _load_network()).isOffline();
if (code === 'ENOTFOUND' && possibleOfflineChange) {
// can't resolve a domain
return true;
}
// used to be able to resolve this domain! something is wrong
if (code === 'ENOTFOUND' && hostname && successHosts[hostname]) {
// can't resolve this domain but we've successfully resolved it before
return true;
}
// network was previously offline and we can't resolve the domain
if (code === 'ENOTFOUND' && controlOffline) {
return true;
}
// connection was reset or dropped
if (code === 'ECONNRESET') {
return true;
}
return false;
}
/**
* Queue up request arguments to be retried. Start a network connectivity timer if there
* isn't already one.
*/
queueForOffline(opts) {
if (!this.offlineQueue.length) {
this.reporter.warn(this.reporter.lang('offlineRetrying'));
this.initOfflineRetry();
}
this.offlineQueue.push(opts);
}
/**
* Begin timers to retry failed requests when we possibly establish network connectivity
* again.
*/
initOfflineRetry() {
setTimeout(() => {
const queue = this.offlineQueue;
this.offlineQueue = [];
for (const opts of queue) {
this.execute(opts);
}
}, 3000);
}
/**
* Execute a request.
*/
execute(opts) {
const params = opts.params;
const reporter = this.reporter;
const buildNext = fn => data => {
fn(data);
this.running--;
this.shiftQueue();
};
const resolve = buildNext(opts.resolve);
const rejectNext = buildNext(opts.reject);
const reject = function (err) {
err.message = `${params.url}: ${err.message}`;
rejectNext(err);
};
//
let calledOnError = false;
const onError = err => {
if (calledOnError) {
return;
}
calledOnError = true;
const attempts = params.retryAttempts || 0;
if (attempts < 5 && this.isPossibleOfflineError(err)) {
params.retryAttempts = attempts + 1;
if (typeof params.cleanup === 'function') {
params.cleanup();
}
this.queueForOffline(opts);
} else {
reject(err);
}
};
if (!params.process) {
const parts = url.parse(params.url);
params.callback = (err, res, body) => {
Iif (err) {
onError(err);
return;
}
successHosts[parts.hostname] = true;
this.reporter.verbose(this.reporter.lang('verboseRequestFinish', params.url, res.statusCode));
Iif (body && typeof body.error === 'string') {
reject(new Error(body.error));
return;
}
Iif (res.statusCode === 403) {
const errMsg = body && body.message || reporter.lang('requestError', params.url, res.statusCode);
reject(new Error(errMsg));
} else {
Iif (res.statusCode === 400 || res.statusCode === 404 || res.statusCode === 401) {
body = false;
}
resolve(body);
}
};
}
if (params.buffer) {
params.encoding = null;
}
let proxy = this.httpProxy;
Eif (params.url.startsWith('https:')) {
proxy = this.httpsProxy || proxy;
}
Iif (proxy) {
params.proxy = proxy;
}
Iif (this.ca != null) {
params.ca = this.ca;
}
Eif (this.cert != null) {
params.cert = this.cert;
}
Eif (this.key != null) {
params.key = this.key;
}
const request = this._getRequestModule();
const req = request(params);
this.reporter.verbose(this.reporter.lang('verboseRequestStart', params.method, params.url));
req.on('error', onError);
const queue = params.queue;
if (queue) {
req.on('data', queue.stillActive.bind(queue));
}
if (params.process) {
params.process(req, resolve, reject);
}
}
/**
* Remove an item from the queue. Create it's request options and execute it.
*/
shiftQueue() {
if (this.running >= this.max || !this.queue.length) {
return;
}
const opts = this.queue.shift();
this.running++;
this.execute(opts);
}
saveHar(filename) {
if (!this.captureHar) {
throw new Error(this.reporter.lang('requestManagerNotSetupHAR'));
}
// No request may have occurred at all.
this._getRequestModule();
invariant(this._requestCaptureHar != null, 'request-capture-har not setup');
this._requestCaptureHar.saveHar(filename);
}
}
exports.default = RequestManager;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | 1 1 1 1 1 7 7 7 7 7 7 1324 7 7 7 7 7 7 7 7 7 7 7 7 7 1317 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
const invariant = require('invariant');
const stream = require('stream');
const zlib = require('zlib');
function hasGzipHeader(chunk) {
return chunk[0] === 0x1F && chunk[1] === 0x8B && chunk[2] === 0x08;
}
class UnpackStream extends stream.Transform {
constructor(options) {
super(options);
this._srcStream = null;
this._readHeader = false;
this.once('pipe', src => {
this._srcStream = src;
});
}
_transform(chunk, encoding, callback) {
if (!this._readHeader) {
this._readHeader = true;
invariant(chunk instanceof Buffer, 'Chunk must be a buffer');
Eif (hasGzipHeader(chunk)) {
// Stop receiving data from the src stream, and pipe it instead to zlib,
// then pipe it's output through us.
const unzipStream = zlib.createUnzip();
unzipStream.on('error', err => this.emit('error', err));
const srcStream = this._srcStream;
invariant(srcStream, 'How? To get here a stream must have been piped!');
srcStream.pipe(unzipStream).pipe(this);
// Unpipe after another stream has been piped so it's always piping to
// something, thus avoiding pausing it.
srcStream.unpipe(this);
unzipStream.write(chunk);
this._srcStream = null;
callback();
return;
}
}
callback(null, chunk);
}
}
exports.UnpackStream = UnpackStream;
class ConcatStream extends stream.Transform {
constructor(done) {
super();
this._data = [];
this._done = done;
}
_transform(chunk, encoding, callback) {
invariant(chunk instanceof Buffer, 'Chunk must be a buffer');
invariant(this._data != null, 'Missing data array');
this._data.push(chunk);
this.push(chunk);
callback();
}
_flush(callback) {
invariant(this._data != null, 'Missing data array');
this._done(Buffer.concat(this._data));
this._data = null;
callback();
}
}
exports.ConcatStream = ConcatStream;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 1 1 1 1 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
const path = require('path');
var _require = require('../constants');
const ROOT_USER = _require.ROOT_USER;
const userHomeDir = process.platform === 'linux' && ROOT_USER ? path.resolve('/usr/local/share') : require('os').homedir();
exports.default = userHomeDir;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| fix.js | 85.08% | (154 / 181) | 72.2% | (148 / 205) | 100% | (15 / 15) | 88.3% | (151 / 171) | |
| index.js | 80.56% | (29 / 36) | 68% | (17 / 25) | 85.71% | (6 / 7) | 80% | (28 / 35) | |
| infer-license.js | 100% | (21 / 21) | 83.33% | (10 / 12) | 100% | (4 / 4) | 100% | (20 / 20) | |
| licenses.js | 100% | (2 / 2) | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (2 / 2) | |
| typos.js | 100% | (2 / 2) | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (2 / 2) | |
| util.js | 67.74% | (42 / 62) | 54.76% | (23 / 42) | 66.67% | (4 / 6) | 68.85% | (42 / 61) | |
| validate.js | 82.28% | (65 / 79) | 60.81% | (45 / 74) | 80% | (8 / 10) | 82.05% | (64 / 78) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 177 177 177 177 177 177 1 177 4 4 4 4 4 24 24 4 177 151 177 22 177 9 177 177 2141 2141 1 177 176 176 176 176 176 176 177 177 3 3 3 3 3 3 3 177 63 177 177 175 177 6 177 61 61 61 61 177 5 5 177 177 177 162 15 177 177 177 162 177 177 18 18 1 1 1 1 3 3 18 18 1 1 1 1 3 3 177 177 177 4 4 5 5 5 5 4 4 2 2 177 177 177 807 807 177 163 163 163 163 163 163 163 163 159 4 3 1 177 176 1 1 1 1 1 177 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _toArray2;
function _load_toArray() {
return _toArray2 = _interopRequireDefault(require('babel-runtime/helpers/toArray'));
}
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _util;
function _load_util() {
return _util = require('./util.js');
}
var _index;
function _load_index() {
return _index = require('../../resolvers/index.js');
}
var _inferLicense;
function _load_inferLicense() {
return _inferLicense = _interopRequireDefault(require('./infer-license.js'));
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../fs.js'));
}
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const semver = require('semver');
const path = require('path');
const url = require('url');
const LICENSE_RENAMES = {
'MIT/X11': 'MIT',
X11: 'MIT'
};
exports.default = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (info, moduleLoc, reporter, warn, looseSemver) {
const files = yield (_fs || _load_fs()).readdir(moduleLoc);
// clean info.version
Iif (typeof info.version === 'string' && !semver.valid(info.version)) {
info.version = semver.clean(info.version, looseSemver) || info.version;
}
// if name or version aren't set then set them to empty strings
info.name = info.name || '';
info.version = info.version || '';
// if the man field is a string then coerce it to an array
Iif (typeof info.man === 'string') {
info.man = [info.man];
}
// if the keywords field is a string then split it on any whitespace
if (typeof info.keywords === 'string') {
info.keywords = info.keywords.split(/\s+/g);
}
// if there's no contributors field but an authors field then expand it
if (!info.contributors && files.indexOf('AUTHORS') >= 0) {
const authorsFilepath = path.join(moduleLoc, 'AUTHORS');
const authorsFilestats = yield (_fs || _load_fs()).stat(authorsFilepath);
Eif (authorsFilestats.isFile()) {
let authors = yield (_fs || _load_fs()).readFile(authorsFilepath);
authors = authors.split(/\r?\n/g) // split on lines
.map(function (line) {
return line.replace(/^\s*#.*$/, '').trim();
}) // remove comments
.filter(function (line) {
return !!line;
}); // remove empty lines
info.contributors = authors;
}
}
// expand people fields to objects
if (typeof info.author === 'string' || typeof info.author === 'object') {
info.author = (0, (_util || _load_util()).normalizePerson)(info.author);
}
if (Array.isArray(info.contributors)) {
info.contributors = info.contributors.map((_util || _load_util()).normalizePerson);
}
if (Array.isArray(info.maintainers)) {
info.maintainers = info.maintainers.map((_util || _load_util()).normalizePerson);
}
// if there's no readme field then load the README file from the cwd
Eif (!info.readme) {
const readmeCandidates = files.filter(function (filename) {
const lower = filename.toLowerCase();
return lower === 'readme' || lower.indexOf('readme.') === 0;
}).sort(function (filename1, filename2) {
// favor files with extensions
return filename2.indexOf('.') - filename1.indexOf('.');
});
for (const readmeFilename of readmeCandidates) {
const readmeFilepath = path.join(moduleLoc, readmeFilename);
const readmeFileStats = yield (_fs || _load_fs()).stat(readmeFilepath);
Eif (readmeFileStats.isFile()) {
info.readmeFilename = readmeFilename;
info.readme = yield (_fs || _load_fs()).readFile(readmeFilepath);
break;
}
}
}
// if there's no description then take the first paragraph from the readme
Iif (!info.description && info.readme) {
const desc = (0, (_util || _load_util()).extractDescription)(info.readme);
if (desc) {
info.description = desc;
}
}
// support array of engine keys
if (Array.isArray(info.engines)) {
const engines = {};
for (const str of info.engines) {
Eif (typeof str === 'string') {
var _str$trim$split = str.trim().split(/ +/g),
_str$trim$split2 = (0, (_toArray2 || _load_toArray()).default)(_str$trim$split);
const name = _str$trim$split2[0],
patternParts = _str$trim$split2.slice(1);
engines[name] = patternParts.join(' ');
}
}
info.engines = engines;
}
// if the repository field is a string then assume it's a git repo and expand it
if (typeof info.repository === 'string') {
info.repository = {
type: 'git',
url: info.repository
};
}
const repo = info.repository;
// explode info.repository.url if it's a hosted git shorthand
if (repo && typeof repo === 'object' && typeof repo.url === 'string') {
repo.url = (0, (_index || _load_index()).hostedGitFragmentToGitUrl)(repo.url, reporter);
}
// allow bugs to be specified as a string, expand it to an object with a single url prop
if (typeof info.bugs === 'string') {
info.bugs = { url: info.bugs };
}
// normalize homepage url to http
if (typeof info.homepage === 'string') {
const parts = url.parse(info.homepage);
parts.protocol = parts.protocol || 'http:';
Iif (parts.pathname && !parts.hostname) {
parts.hostname = parts.pathname;
parts.pathname = '';
}
info.homepage = url.format(parts);
}
// if the `bin` field is as string then expand it to an object with a single property
// based on the original `bin` field and `name field`
// { name: "foo", bin: "cli.js" } -> { name: "foo", bin: { foo: "cli.js" } }
if (typeof info.name === 'string' && typeof info.bin === 'string') {
// Remove scoped package name for consistency with NPM's bin field fixing behaviour
const name = info.name.replace(/^@[^\/]+\//, '');
info.bin = { [name]: info.bin };
}
// bundleDependencies is an alias for bundledDependencies
Iif (info.bundledDependencies) {
info.bundleDependencies = info.bundledDependencies;
delete info.bundledDependencies;
}
let scripts;
// dummy script object to shove file inferred scripts onto
if (info.scripts && typeof info.scripts === 'object') {
scripts = info.scripts;
} else {
scripts = {};
}
// if there's a server.js file and no start script then set it to `node server.js`
Iif (!scripts.start && files.indexOf('server.js') >= 0) {
scripts.start = 'node server.js';
}
// if there's a binding.gyp file and no install script then set it to `node-gyp rebuild`
Iif (!scripts.install && files.indexOf('binding.gyp') >= 0) {
scripts.install = 'node-gyp rebuild';
}
// set scripts if we've polluted the empty object
if (Object.keys(scripts).length) {
info.scripts = scripts;
}
const dirs = info.directories;
if (dirs && typeof dirs === 'object') {
const binDir = dirs.bin;
if (!info.bin && binDir && typeof binDir === 'string') {
const bin = info.bin = {};
const fullBinDir = path.join(moduleLoc, binDir);
Eif (yield (_fs || _load_fs()).exists(fullBinDir)) {
for (const scriptName of yield (_fs || _load_fs()).readdir(fullBinDir)) {
Iif (scriptName[0] === '.') {
continue;
}
bin[scriptName] = path.join('.', binDir, scriptName);
}
} else {
warn(reporter.lang('manifestDirectoryNotFound', binDir, info.name));
}
}
const manDir = dirs.man;
if (!info.man && typeof manDir === 'string') {
const man = info.man = [];
const fullManDir = path.join(moduleLoc, manDir);
Eif (yield (_fs || _load_fs()).exists(fullManDir)) {
for (const filename of yield (_fs || _load_fs()).readdir(fullManDir)) {
Eif (/^(.*?)\.[0-9]$/.test(filename)) {
man.push(path.join('.', manDir, filename));
}
}
} else {
warn(reporter.lang('manifestDirectoryNotFound', manDir, info.name));
}
}
}
delete info.directories;
// normalize licenses field
const licenses = info.licenses;
if (Array.isArray(licenses) && !info.license) {
let licenseTypes = [];
for (let license of licenses) {
Eif (license && typeof license === 'object') {
license = license.type;
}
Eif (typeof license === 'string') {
licenseTypes.push(license);
}
}
licenseTypes = licenseTypes.filter((_util || _load_util()).isValidLicense);
if (licenseTypes.length === 1) {
info.license = licenseTypes[0];
} else Iif (licenseTypes.length) {
info.license = `(${licenseTypes.join(' OR ')})`;
}
}
const license = info.license;
// normalize license
Iif (license && typeof license === 'object') {
info.license = license.type;
}
// get license file
const licenseFile = files.find(function (filename) {
const lower = filename.toLowerCase();
return lower === 'license' || lower.startsWith('license.') || lower === 'unlicense' || lower.startsWith('unlicense.');
});
if (licenseFile) {
const licenseFilepath = path.join(moduleLoc, licenseFile);
const licenseFileStats = yield (_fs || _load_fs()).stat(licenseFilepath);
Eif (licenseFileStats.isFile()) {
const licenseContent = yield (_fs || _load_fs()).readFile(licenseFilepath);
const inferredLicense = (0, (_inferLicense || _load_inferLicense()).default)(licenseContent);
info.licenseText = licenseContent;
const license = info.license;
if (typeof license === 'string') {
Iif (inferredLicense && (0, (_util || _load_util()).isValidLicense)(inferredLicense) && !(0, (_util || _load_util()).isValidLicense)(license)) {
// some packages don't specify their license version but we can infer it based on their license file
const basicLicense = license.toLowerCase().replace(/(-like|\*)$/g, '');
const expandedLicense = inferredLicense.toLowerCase();
if (expandedLicense.startsWith(basicLicense)) {
// TODO consider doing something to notify the user
info.license = inferredLicense;
}
}
} else if (inferredLicense) {
// if there's no license then infer it based on the license file
info.license = inferredLicense;
} else {
// valid expression to refer to a license in a file
info.license = `SEE LICENSE IN ${licenseFile}`;
}
}
}
if (typeof info.license === 'string') {
// sometimes licenses are known by different names, reduce them
info.license = LICENSE_RENAMES[info.license] || info.license;
} else Eif (typeof info.readme === 'string') {
// the license might be at the bottom of the README
const inferredLicense = (0, (_inferLicense || _load_inferLicense()).default)(info.readme);
Eif (inferredLicense) {
info.license = inferredLicense;
}
}
});
return function (_x, _x2, _x3, _x4, _x5) {
return _ref.apply(this, arguments);
};
})();
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | 1 1 1 1 1 1 1 1 1 1 3 1 1 1 177 177 177 177 177 177 177 1 177 177 177 177 1 177 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
var _validate;
function _load_validate() {
return _validate = _interopRequireDefault(require('./validate.js'));
}
var _fix;
function _load_fix() {
return _fix = _interopRequireDefault(require('./fix.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const path = require('path');
exports.default = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (info, moduleLoc, config, isRoot) {
// create human readable name
const name = info.name,
version = info.version;
let human;
Eif (typeof name === 'string') {
human = name;
}
Eif (human && typeof version === 'string' && version) {
human += `@${version}`;
}
Iif (isRoot && info._loc) {
human = path.relative(config.cwd, info._loc);
}
function warn(msg) {
if (human) {
msg = `${human}: ${msg}`;
}
config.reporter.warn(msg);
}
yield (0, (_fix || _load_fix()).default)(info, moduleLoc, config.reporter, warn, config.looseSemver);
try {
(0, (_validate || _load_validate()).default)(info, isRoot, config.reporter, warn);
} catch (err) {
if (human) {
err.message = `${human}: ${err.message}`;
}
throw err;
}
return info;
});
return function (_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 1 1 1 1 1 1 1 164 1 1 164 164 702 702 109 55 237 321 35 20 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = inferLicense;
var _licenses;
function _load_licenses() {
return _licenses = _interopRequireDefault(require('./licenses.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function clean(str) {
return str.replace(/[^A-Za-z\s]/g, ' ').replace(/[\s]+/g, ' ').trim().toLowerCase();
}
const REGEXES = {
Unlicense: [/http:\/\/unlicense.org\//],
WTFPL: [/DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE/, /WTFPL\b/],
ISC: [/The ISC License/, /ISC\b/],
Apache: [/Apache License\b/],
MIT: [/MIT\b/],
BSD: [/BSD\b/]
};
function inferLicense(license) {
// check if we have any explicit licenses
const cleanLicense = clean(license);
for (const licenseName in (_licenses || _load_licenses()).default) {
const testLicense = (_licenses || _load_licenses()).default[licenseName];
if (cleanLicense.search(testLicense) >= 0) {
return licenseName;
}
}
// infer based on some keywords
for (const licenseName in REGEXES) {
for (const regex of REGEXES[licenseName]) {
if (license.search(regex) >= 0) {
return `${licenseName}*`;
}
}
}
return null;
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/* eslint-disable max-len */
/**
* DO NOT EDIT THIS FILE MANUALLY.
* THIS FILE WAS GENERATED BY "generate-licenses-js.js".
*/
exports.default = {
'Apache-2.0': new RegExp('(licensed under the apache license version the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license$|apache license version january http www apache org licenses terms and conditions for use reproduction and distribution definitions license shall mean the terms and conditions for use reproduction and distribution as defined by sections through of this document licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the license legal entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity for the purposes of this definition control means i the power direct or indirect to cause the direction or management of such entity whether by contract or otherwise or ii ownership of fifty percent or more of the outstanding shares or iii beneficial ownership of such entity you or your shall mean an individual or legal entity exercising permissions granted by this license source form shall mean the preferred form for making modifications including but not limited to software source code documentation source and configuration files object form shall mean any form resulting from mechanical transformation or translation of a source form including but not limited to compiled object code generated documentation and conversions to other media types work shall mean the work of authorship whether in source or object form made available under the license as indicated by a copyright notice that is included in or attached to the work an example is provided in the appendix below derivative works shall mean any work whether in source or object form that is based on or derived from the work and for which the editorial revisions annotations elaborations or other modifications represent as a whole an original work of authorship for the purposes of this license derivative works shall not include works that remain separable from or merely link or bind by name to the interfaces of the work and derivative works thereof contribution shall mean any work of authorship including the original version of the work and any modifications or additions to that work or derivative works thereof that is intentionally submitted to licensor for inclusion in the work by the copyright owner or by an individual or legal entity authorized to submit on behalf of the copyright owner for the purposes of this definition submitted means any form of electronic verbal or written communication sent to the licensor or its representatives including but not limited to communication on electronic mailing lists source code control systems and issue tracking systems that are managed by or on behalf of the licensor for the purpose of discussing and improving the work but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as not a contribution contributor shall mean licensor and any individual or legal entity on behalf of whom a contribution has been received by licensor and subsequently incorporated within the work grant of copyright license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable copyright license to reproduce prepare derivative works of publicly display publicly perform sublicense and distribute the work and such derivative works in source or object form grant of patent license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable except as stated in this section patent license to make have made use offer to sell sell import and otherwise transfer the work where such license applies only to those patent claims licensable by such contributor that are necessarily infringed by their contribution s alone or by combination of their contribution s with the work to which such contribution s was submitted if you institute patent litigation against any entity including a cross claim or counterclaim in a lawsuit alleging that the work or a contribution incorporated within the work constitutes direct or contributory patent infringement then any patent licenses granted to you under this license for that work shall terminate as of the date such litigation is filed redistribution you may reproduce and distribute copies of the work or derivative works thereof in any medium with or without modifications and in source or object form provided that you meet the following conditions a you must give any other recipients of the work or derivative works a copy of this license and b you must cause any modified files to carry prominent notices stating that you changed the files and c you must retain in the source form of any derivative works that you distribute all copyright patent trademark and attribution notices from the source form of the work excluding those notices that do not pertain to any part of the derivative works and d if the work includes a notice text file as part of its distribution then any derivative works that you distribute must include a readable copy of the attribution notices contained within such notice file excluding those notices that do not pertain to any part of the derivative works in at least one of the following places within a notice text file distributed as part of the derivative works within the source form or documentation if provided along with the derivative works or within a display generated by the derivative works if and wherever such third party notices normally appear the contents of the notice file are for informational purposes only and do not modify the license you may add your own attribution notices within derivative works that you distribute alongside or as an addendum to the notice text from the work provided that such additional attribution notices cannot be construed as modifying the license you may add your own copyright statement to your modifications and may provide additional or different license terms and conditions for use reproduction or distribution of your modifications or for any such derivative works as a whole provided your use reproduction and distribution of the work otherwise complies with the conditions stated in this license submission of contributions unless you explicitly state otherwise any contribution intentionally submitted for inclusion in the work by you to the licensor shall be under the terms and conditions of this license without any additional terms or conditions notwithstanding the above nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with licensor regarding such contributions trademarks this license does not grant permission to use the trade names trademarks service marks or product names of the licensor except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the notice file disclaimer of warranty unless required by applicable law or agreed to in writing licensor provides the work and each contributor provides its contributions on an as is basis without warranties or conditions of any kind either express or implied including without limitation any warranties or conditions of title non infringement merchantability or fitness for a particular purpose you are solely responsible for determining the appropriateness of using or redistributing the work and assume any risks associated with your exercise of permissions under this license limitation of liability in no event and under no legal theory whether in tort including negligence contract or otherwise unless required by applicable law such as deliberate and grossly negligent acts or agreed to in writing shall any contributor be liable to you for damages including any direct indirect special incidental or consequential damages of any character arising as a result of this license or out of the use or inability to use the work including but not limited to damages for loss of goodwill work stoppage computer failure or malfunction or any and all other commercial damages or losses even if such contributor has been advised of the possibility of such damages accepting warranty or additional liability while redistributing the work or derivative works thereof you may choose to offer and charge a fee for acceptance of support warranty indemnity or other liability obligations and or rights consistent with this license however in accepting such obligations you may act only on your own behalf and on your sole responsibility not on behalf of any other contributor and only if you agree to indemnify defend and hold each contributor harmless for any liability incurred by or claims asserted against such contributor by reason of your accepting any such warranty or additional liability end of terms and conditions$)', 'g'),
'BSD-2-Clause': new RegExp('(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this(.*?| )is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this(.*?| )even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$)', 'g'),
'BSD-3-Clause': new RegExp('(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name of(.*?| )nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution the names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall the copyright holders and contributors be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name(.*?| )nor the names of(.*?| )contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by(.*?| )as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$))', 'g'),
'MIT': new RegExp('permission is hereby granted free of charge to any person obtaining a copy of this software and associated documentation files the software to deal in the software without restriction including without limitation the rights to use copy modify merge publish distribute sublicense and or sell copies of the software and to permit persons to whom the software is furnished to do so subject to the following conditions the above copyright notice and this permission notice shall be included in all copies or substantial portions of the software the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors or copyright holders be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software$', 'g'),
'Unlicense': new RegExp('this is free and unencumbered software released into the public domain anyone is free to copy modify publish use compile sell or distribute this software either in source code form or as a compiled binary for any purpose commercial or non commercial and by any means in jurisdictions that recognize copyright laws the author or authors of this software dedicate any and all copyright interest in the software to the public domain we make this dedication for the benefit of the public at large and to the detriment of our heirs and successors we intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software for more information please refer to wildcard$', 'g')
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
dependancies: 'dependencies',
dependecies: 'dependencies',
depdenencies: 'dependencies',
devEependencies: 'devDependencies',
depends: 'dependencies',
'dev-dependencies': 'devDependencies',
devDependences: 'devDependencies',
devDepenencies: 'devDependencies',
devdependencies: 'devDependencies',
repostitory: 'repository',
repo: 'repository',
prefereGlobal: 'preferGlobal',
hompage: 'homepage',
hampage: 'homepage',
autohr: 'author',
autor: 'author',
contributers: 'contributors',
publicationConfig: 'publishConfig',
script: 'scripts'
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | 1 1 1 1 1 1 1 1 1 252 1 227 164 63 63 63 63 63 46 63 63 49 63 1 227 227 227 227 226 226 226 227 227 196 227 227 133 227 1 227 1 1 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isValidLicense = isValidLicense;
exports.stringifyPerson = stringifyPerson;
exports.parsePerson = parsePerson;
exports.normalizePerson = normalizePerson;
exports.extractDescription = extractDescription;
exports.extractRepositoryUrl = extractRepositoryUrl;
const validateLicense = require('validate-npm-package-license');
function isValidLicense(license) {
return !!license && validateLicense(license).validForNewPackages;
}
function stringifyPerson(person) {
if (!person || typeof person !== 'object') {
return person;
}
const parts = [];
Eif (person.name) {
parts.push(person.name);
}
const email = person.email || person.mail;
if (typeof email === 'string') {
parts.push(`<${email}>`);
}
const url = person.url || person.web;
if (typeof url === 'string') {
parts.push(`(${url})`);
}
return parts.join(' ');
}
function parsePerson(person) {
Iif (typeof person !== 'string') {
return person;
}
// format: name (url) <email>
const obj = {};
let name = person.match(/^([^\(<]+)/);
if (name) {
name = name[0].trim();
Eif (name) {
obj.name = name;
}
}
const email = person.match(/<([^>]+)>/);
if (email) {
obj.email = email[1];
}
const url = person.match(/\(([^\)]+)\)/);
if (url) {
obj.url = url[1];
}
return obj;
}
function normalizePerson(person) {
return parsePerson(stringifyPerson(person));
}
function extractDescription(readme) {
if (typeof readme !== 'string' || readme === '') {
return undefined;
}
// split into lines
const lines = readme.trim().split('\n').map(line => line.trim());
// find the start of the first paragraph, ignore headings
let start = 0;
for (; start < lines.length; start++) {
const line = lines[start];
if (line && line.match(/^(#|$)/)) {
// line isn't empty and isn't a heading so this is the start of a paragraph
start++;
break;
}
}
// skip newlines from the header to the first line
while (start < lines.length && !lines[start]) {
start++;
}
// continue to the first non empty line
let end = start;
while (end < lines.length && lines[end]) {
end++;
}
return lines.slice(start, end).join(' ');
}
function extractRepositoryUrl(repository) {
if (!repository || typeof repository !== 'object') {
return repository;
}
return repository.url;
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | 1 1 1 1 1 1 177 1 19 177 177 177 177 177 177 177 177 1 1 1 177 354 354 177 1 1 1 1 1 1 1 1 1 2 1 1 1 1 177 1 1 177 1 378 378 1134 1134 546 588 378 588 588 588 588 1848 1848 3265 3265 3265 3265 3265 3260 5 5 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray2;
function _load_slicedToArray() {
return _slicedToArray2 = _interopRequireDefault(require('babel-runtime/helpers/slicedToArray'));
}
exports.isValidPackageName = isValidPackageName;
exports.default = function (info, isRoot, reporter, warn) {
if (isRoot) {
for (const key in (_typos || _load_typos()).default) {
Iif (key in info) {
warn(reporter.lang('manifestPotentialTypo', key, (_typos || _load_typos()).default[key]));
}
}
}
// validate name
const name = info.name;
Eif (typeof name === 'string') {
Iif (isRoot && isBuiltinModule(name)) {
warn(reporter.lang('manifestBuiltinModule', name));
}
// cannot start with a dot
Iif (name[0] === '.') {
throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestNameDot'));
}
// cannot contain the following characters
Iif (!isValidPackageName(name)) {
throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestNameIllegalChars'));
}
// cannot equal node_modules or favicon.ico
const lower = name.toLowerCase();
Iif (lower === 'node_modules' || lower === 'favicon.ico') {
throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestNameBlacklisted'));
}
}
// validate license
if (isRoot && !info.private) {
Eif (typeof info.license === 'string') {
const license = info.license.replace(/\*$/g, '');
Iif (!(0, (_util || _load_util()).isValidLicense)(license)) {
warn(reporter.lang('manifestLicenseInvalid'));
}
} else {
warn(reporter.lang('manifestLicenseNone'));
}
}
// validate strings
for (const key of strings) {
const val = info[key];
Iif (val && typeof val !== 'string') {
throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestStringExpected', key));
}
}
cleanDependencies(info, isRoot, reporter, warn);
};
exports.cleanDependencies = cleanDependencies;
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _util;
function _load_util() {
return _util = require('./util.js');
}
var _typos;
function _load_typos() {
return _typos = _interopRequireDefault(require('./typos.js'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const isBuiltinModule = require('is-builtin-module');
const strings = ['name', 'version'];
const dependencyKeys = [
// npm registry will include optionalDependencies in dependencies and we'll want to dedupe them from the
// other fields first
'optionalDependencies',
// it's seemingly common to include a dependency in dependencies and devDependencies of the same name but
// different ranges, this can cause a lot of issues with our determinism and the behaviour of npm is
// currently unspecified.
'dependencies', 'devDependencies'];
function isValidName(name) {
return !name.match(/[\/@\s\+%:]/) && encodeURIComponent(name) === name;
}
function isValidScopedName(name) {
if (name[0] !== '@') {
return false;
}
const parts = name.slice(1).split('/');
return parts.length === 2 && isValidName(parts[0]) && isValidName(parts[1]);
}
function isValidPackageName(name) {
return isValidName(name) || isValidScopedName(name);
}
function cleanDependencies(info, isRoot, reporter, warn) {
// get dependency objects
const depTypes = [];
for (const type of dependencyKeys) {
const deps = info[type];
if (!deps || typeof deps !== 'object') {
continue;
}
depTypes.push([type, deps]);
}
// ensure that dependencies don't have ones that can collide
for (const _ref of depTypes) {
var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2);
const type = _ref2[0];
const deps = _ref2[1];
for (const name in deps) {
const version = deps[name];
// check collisions
for (const _ref3 of depTypes) {
var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2);
const type2 = _ref4[0];
const deps2 = _ref4[1];
const version2 = deps2[name];
if (deps === deps2 || !version2 || version2 === '*') {
continue;
}
Iif (version !== version2 && isRoot) {
// only throw a warning when at the root
warn(reporter.lang('manifestDependencyCollision', type, name, version, type2, version2));
}
delete deps2[name];
}
}
}
}
|